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}$/;
8
  • 1
    dose not work - This is of no use. Please include what the actual problem is. Commented Apr 6, 2015 at 7:21
  • 1
    this won't actually need a regex. Commented Apr 6, 2015 at 7:24
  • 1
    @vks - How many years old is a two-month old baby? Vilas - what is the \S for in your regex? Commented Apr 6, 2015 at 7:27
  • \S will not allows space at first in textbox and I will also consider baby age so suggest me regex for age validation (I used 0 for baby). Commented Apr 6, 2015 at 7:33
  • @VilasGalave you mean it is people? If you are validating input, do you get user to re-confirm? Commented Apr 6, 2015 at 7:38

4 Answers 4

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
}
Sign up to request clarification or add additional context in comments.

Comments

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
}

1 Comment

@nnnnnn:- Already removed that part after watching your comment. Thanks!
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>

 

4 Comments

\S will match any non-space character.
\s matches any space character.
@AvinashRaj I belive OP had it for a reason.
@IoannisTsiokos which browser are you using? I just tried it in Chrome and it worked - try input 300 and hit submit.
0

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

if( input >=0 && input <= 200 ) {
    //its valid
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.