loveNoHate
loveNoHate

Reputation: 1547

Why is my Javascript RegEx quantifier "not working"?

This question seems to have such an easy answer and an ashaming one for me, that I hope you just comment, then I can delete the thread after solving. ;)

I have a problem with the {n} quantifier in my RegEx. It does not seem to work!

Here my code

document.time.Id.onkeyup = function() {
  var that = this.value,
      regex = /^[1-9]{1}/
  if (that) {   
      if (!that.match(regex)) {
          this.nextSibling.innerHTML="Number must be between '1' and '100'.";
      } else {
          this.nextSibling.innerHTML="";
      }
  } else {
      this.nextSibling.innerHTML="";
  } 
}

As you can see, I want to match against 1 till 100 in the end, but I am stuck at the bit, that the quantifier does not work. When I key in 0 there is a match failure, as well with any letter...so it does work "a bit".

Can you please help me?

Upvotes: 1

Views: 944

Answers (2)

Marius Schulz
Marius Schulz

Reputation: 16440

Your regular expression says to match any string that starts (because it's anchored at the beginning using ^) with any digit between 1 and 9. This is why it doesn't match 0 or letters.

A range validation is something you'd want to check using basic number comparisons:

var numberValue = parseInt(this.value, 10);
if (numberValue >= 1 && numberValue <= 100) {
    // valid number
}

For the sake of completeness, you could create a regular expression for that purpose which I don't recommend, though:

^(?:[1-9][0-9]?|100)$

Upvotes: 4

Jerry
Jerry

Reputation: 71538

Try using this regex instead:

^[1-9][0-9]?$|^100$

The quantifier you used is actually redundant, since [1-9] and [1-9]{1} mean the same thing.

If you input 1000 with your current code and regex, the number will pass because a match counts as long as the regex matches any part of the string. Using $ (end of line anchor) forces the regex to check the whole string.

But you should probably be using a simple if check for that.

if (that > 0 && that <= 100 && that % 1 == 0) {
    ...
}

Upvotes: 2

Related Questions