This question has already been answered:

You need to set a regular expression for a range of numbers from 1 to 32. If the number is larger or smaller, you need to return false.

Reported as a duplicate by ReinRaus , PashaPash members 13 May '16 at 20:25 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

  • one
    what is the problem? :) - Grundy
  • one
    @Grundy, here they want to get a ready-made answer, even without trying to solve the problem) - Denis Bubnov
  • A lot of such questions. Use the snippet from the specified question to generate any range, not 1 ... 32 - ReinRaus

3 answers 3

To check that a value is in a certain range, it is better to bring it to a number and then check.

var v = parseInt(value); if(v>=1 && v=<32) return true; return false; 

If you really want to use a regular expression, you can use the following

 /^(1|2|3|4|5|6|7|8|9|10|11|12|13|14|15|16|17|18|19|20|21|22|23|24|25|26|27|28|29|30|31|32)$/ 
  • 3
    Why so? /^([1-2]?[\d]|3[0-2])$/ :) - user207618
  • 2
    @Other, you have 0 suited, but this is not true. - VenZell
  • @Other, because the easiest option :-) you can add an answer with your own version - Grundy
  • one
    @VenZell, hmm, really, probably: ^([1-9]|[1-2][\d]|3[0-2])$ - user207618
  • @VenZell, oh how did the geniuses think the same way? You have not copied. - user207618
 /^([1-9]|[1-2][\d]|3[0-2])$/ 

[1-9] - numbers from 1 to 9
| - OR
[1-2][\d] - numbers from 10 to 29
| - OR
3[0-2] - numbers from 30 to 32

Alternative option

 /^([1-2]?[1-9]|[1-3][0-2])$/ 

[1-2]?[1-9] - numbers from 1 to 9, numbers from 11 to 19, numbers from 21 to 29
| - OR
[1-3][0-2] - numbers from 10 to 12, numbers from 20 to 22, numbers from 30 to 32

  • Is it possible to reduce more? - Grundy
  • @Grundy, I will try and update the answer - VenZell
  • @Grundy, and where can you cut it? - user207618
  • There is nothing if there is something else in the line besides numbers, a demonstration . And why should the \d metacharacter be wrapped in parentheses? My example: \b([1-9]|[1-2]\d|3[0-2])\b - demonstration . - Sasha Chernykh
  • you can still remove the hyphen between 1 and 2 - more - a symbol :) - splash58

32 is the same power of two, you can check the bits:

 32 100000 31 011111 30 011110 .. 2 000010 1 000001 

The number minus 1 should be from 0 to 31: from 00000 to 11111 .

 if( ((x - 1) & 0x1F) === (x - 1)) { // OK } else { // NOT OK } 
  • 32 This is a string - Grundy
  • @Grundy as soon as he sees (x - 1) , suddenly becomes a number - Sergiks
  • logical .... :-) - Grundy