3

I want a regex that allows users to enter only numbers between 0 and 200. I've tried this but it doesn't work:

var age_regex=/^\S[0-9]{0,3}$/;
ManoDestra
  • 6,325
  • 6
  • 26
  • 50
Vg.
  • 133
  • 2
  • 3
  • 17

4 Answers4

4

Instead of regex, you can compare numerical value itself:

var ageValue = 50; // get the input age here
var ageNumericVal = +ageValue;
if (ageNumericVal < 0 || ageNumericVal > 200) {
  // invalid
}
Pramod Karandikar
  • 5,289
  • 7
  • 43
  • 68
2

I strongly recommend using an if statement for this since regex is not efficient for this case.

Anyway, if you really want to use RegEx, try the following:

var age_regex=/\s[0-1]{1}[0-9]{0,2}/;

Regex demo and explanation.

EDIT:

Using this regex in <input>:

(Working Demo)

p{
  color: red;
}
<form action="#">
  Enter Age: <input type="text" name="number" pattern="[0-1]{1}[0-9]{0,2}" title="Please enter a valid number between 0 and 200.">
  <input type="submit">
</form>

<p>This form will give error if number does not pass the regex.</p>

 

Arno Chauveau
  • 990
  • 9
  • 14
Rahul Desai
  • 15,242
  • 19
  • 83
  • 138
2

You can try this:

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

An easy fix to check age would be not to use regex and simply check like this:

if(age >= 0 &&  age <= 200)  
{
   //code
}
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
0

you could simply check in if condition without need for regex, as:

if( input >=0 && input <= 200 ) {
    //its valid
}
Sudhir Bastakoti
  • 99,167
  • 15
  • 158
  • 162