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}$/;
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}$/;
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
}
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}/;
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>
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
}
you could simply check in if
condition without need for regex, as:
if( input >=0 && input <= 200 ) {
//its valid
}