regexvalidationdigits

Regex for number check below a value (12)


I need to validate a number input to two characters and it can't be more than the value 12.

The two numbers easy:

/^\d{1,2}$/

Then check that if there are two numbers then the first must be either 0 or 1, and the second must be either 0, 1, or 2. That part I don't know how to express, regularly...

And also if possible I would like to have it in single regex statement.


Solution

  • Regex is not suited to dealing with ranges like this, but anyway this should work:

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

    Description:

    ^       match start of the string
    (0?     optional zero
    [1-9]       any number between 1 and 9
    |1[012])    or match 1 followed by either a 0, 1, 2 i.e. 10, 11, 12.
    $           match end of string