Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for 1-10 in javascript for validation

What would be the regex for numbers ranging 1-10 and 1-5? Please help this troubled soul.

like image 465
Hriskesh Ashokan Avatar asked May 29 '11 14:05

Hriskesh Ashokan


3 Answers

You could achive that with easy number checks in javascript:

// Convert input to integer just to be sure
mynum = parseInt(mynum, 10);

// Check number-range
if(mynum >= 1 && mynum <=10)
and
if(mynum >= 1 && mynum <=5)

If you really want to use regex:

/^([1-9]|10)$/
and
/^[1-5]$/

UPDATE:

  • Fixed the first regex to correctly match the string boundings
  • Added parseInt to the first example to ensure correct number-checks
like image 69
marsbear Avatar answered Sep 23 '22 19:09

marsbear


This is not a good use of Regular Expressions.

Use simple conditions:

if (x > 0 && x < 6) {
  // x is 1 - 5
}

if (x > 0 && x < 10) {
  // x is 1 - 10
}
like image 24
Jason McCreary Avatar answered Sep 19 '22 19:09

Jason McCreary


For 1-5 you only need to enclose it as character class:

  /^[1-5]$/

For 1-10 you'd just need an additional alternative:

  /^([1-9]|10)$/
like image 25
mario Avatar answered Sep 20 '22 19:09

mario