0

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

Nasir
  • 4,785
  • 10
  • 35
  • 39

3 Answers3

1

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.

eykanal
  • 26,437
  • 19
  • 82
  • 113
  • I'm just looking to change the RegEx in the code where it says `/10|11|12/` – Nasir Jul 19 '11 at 11:23
  • I'm sorry I wont be able to use your solution as I have to exclude 100, two digit numbers...your code will become far too long – Nasir Jul 19 '11 at 12:18
  • @nasir - still disagree, added a bit. I see you've gotten this working, but I would still recommend against it in the future. – eykanal Jul 19 '11 at 12:56
0

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;
    }
});
bliof
  • 2,957
  • 2
  • 23
  • 39
0

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

Community
  • 1
  • 1
Nasir
  • 4,785
  • 10
  • 35
  • 39