Regex for 1-10 in javascript for validation

What will be the regular expression for numbers ranging from 1 to 10 and from 1 to 5? Please help this troubled soul.

+8
javascript regex
source share
7 answers

You can achieve this with simple 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:

  • Correct correspondence of the first regular expression to string constraints fixed
  • Added parseInt to the first example to provide correct number checks.
+11
source share

It is not very convenient to use regular expressions.

Use simple conditions:

 if (x > 0 && x < 6) { // x is 1 - 5 } if (x > 0 && x < 10) { // x is 1 - 10 } 
+4
source share

For 1-5, you just need to wrap it in a character class:

  /^[1-5]$/ 

For 1-10, you just need an additional alternative:

  /^([1-9]|10)$/ 
+3
source share

Is there a reason you want to use regular expressions?

 /([1-9]|10)/ 
+2
source share

Use a numerical comparison. The following number extension can check if a number of two values ​​falls:

 Number.prototype.between = function(lower,upper, includeBoundaries){ lower = Number(lower); upper = Number(upper); noCando = isNaN(lower) || isNaN(upper) || lower>=upper; if ( noCando ) { throw 'wrong arguments or out of range'; } return includeBoundaries ? this >= lower && this <= upper : this > lower && this < upper }; // usage: (12).between(1,12); /=> false (12).between(1,12,true); /=> true (12).between(0,15,true); /=> true (0).between(-5,1); //=> true 

The function converts the parameters to a number, because 0 can be calculated in boolean in javascript in order to be able to check whether the variables are real numerical values ​​and to check if the lower value is at most / equal to the upper one. In these cases, an error occurs.

The includeBoundaries parameter also checks if the number is equal to lower or upper, if it is not specified, the function returns a real check between.

+1
source share

The answer will be

 /^([1-9]|10)$/ 
+1
source share

Within 1-10 it can be

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

and for 1-5 just

 /^[1-5]$/ 
0
source share

All Articles