Reputation: 4865
I have this piece of code:
$('.numeric-year').keyup(function () {
$(this).toggleClass('field-error', /10|11|12/.test(this.value));
});
What I'd like to do is exclude a given set of numbers(e.g 10, 11, 12) from triggering the .toggleClass()
function.
This question is solely to do with RegEx as the rest of the code is working. Sorry I'm terrible at RegEx stuff...learning slowly.
Any help would greatly be appreciated, Thanks
Upvotes: 0
Views: 255
Reputation: 2987
You can try using positive or negative lookahead.
Lets say that you have 3 input fields:
<input type="text" value="2020" />
<input type="text" value="2010" />
<input type="text" value="2000" />
And you want to get the elements with different value than 2010 and 2000, you can do something like this:
$("input").filter(function() {
if(!this.value.match("(?=2010|2000)")) {
return this;
}
});
Upvotes: 0
Reputation: 27017
This particular case would probably be better served using a conditional based on $(this).value
.
Regular expressions are a pattern matching service. If you want to check whether $x
follows a specific pattern, use regexp. In your case, though, you're trying to check whether the value of a given string is equal to one of a couple values. While this could be accomplished using regexp (as bliof said, check for the presence of 1[0-2]
, and if true, don't run), that's a bad habit to get into... that is the job for a string comparison tool, not regex. It be possible, but it's going to be more kludgy, and in other situations this type of thinking may lead to a lot of problems and head-scratching. I would just use
$(this).value() != 10 || $(this).value() != 11 || $(this).value() != 12
Based on your reply, I would still not recommend regex, but the .inArray()
construct, which is more appropriate for your situation.
Upvotes: 1
Reputation: 4865
After having a stab at it myself I came up with this solution
$(this).toggleClass('field-error', !/10|11|12/.test(this.value));
based on Justin Poliey's answer( Regular Expression to exclude set of Keywords ) telling me NOT to negate in the RegEx but in my code.
Hence the !
before the regex /10|11|12/
and it worked a charm. Thanks for your effort guys...Much Appreciated
Upvotes: 0