Search code examples
javascriptregexnumbersdecimalyup

Javascript Decimal Place Restriction To Specific Number With Regex


I have some client-side validation against a input type number which

  • Will accept any number 0 through 99 with 2 decimal places
  • And the values of the decimals must be .00, .25, .33, .5, .67, .75

I've tried with 2 digit length validation but how can I validate specific list of decimal numbers with regex ?

/^\d{1,2}(\.\d{1,2})?$/

VALID CASES

5.25

78.5

99.75

INVALID CASES

88.12

50.78


Solution

  • You could write the pattern as:

    ^\d{1,2}\.(?:00|[72]5|33|67|50?)$
    

    Explanation

    • ^ Start of string
    • \d{1,2} Match 1 or 2 digits
    • \. Match a dot
    • (?: Non capture group for the alternatives
      • 00|[72]5|33|67|50? match 00 75 25 33 67 5 or 50
    • ) Close the non capture group
    • $ End of string

    Regex demo