Search code examples
regexvalidationdecimaluser-inputnegative-number

Validating User Input While Typing using RegEx


I am struggling to write the RegEx for the following criteria:

  • The number can be positive / negative
  • Optional - at the start
  • Between 1 and 5 numbers before the decimal point
  • 2 decimal places only (optional)
  • Stop user from typing more than 1 . or -

This is the regex I have tried to implement which does not work for me.

^((-?[0-9]{1,5}(\.?){1,1}[0-9]{0,2})

It should allow the user to type out the following numbers.

-1.12
12345
1
123
12.12

Any help would be appreciated!


Solution

  • You may use

    ^-?\d{0,5}(?:(?<=\d)\.\d{0,2})?$
    

    See the regex demo.

    Details

    • ^ - start of string
    • -? - an optional -
    • \d{0,5} - zero to five digits
    • (?:(?<=\d)\.\d{0,2})? - an optional sequence of
      • (?<=\d) - there must be a digit immediately to the left of the current location
      • \. - a dot
      • \d{0,2} - zero, one or two digits
    • $ - end of string.