Search code examples
regexnumeric

Allow more digit after the first 0 with live input validation regex


I have a regex for some verification on my end. It is

^(?![.,])-?[1-9]*?0?[,.]?([,.]\d+)?$

This regex basically validates a number

  • if it starts with 0, a comma or dot must follow
    • Valid => 0.12 or 0,456
    • Invalid => 012.90
  • cannot have multiple dot or comma in a row e.g. 12..45
  • can only a digit or a comma or a dot e.g. 123, 123.45 or 123,45
  • can't start and end with a dot or comma

This regex perfectly works for above points but I got stuck on one case which is I can't type a number like 100 or 101 because it still expects me a dot or comma as regex still treats any zero as the first rule. How do I fix it?


Solution

  • You can use

    ^(?:0|[1-9]\d*)(?:[.,]\d*)?$
    

    See the regex demo.

    Details:

    • ^ - start of string
    • (?:0|[1-9]\d*) - either
      • 0 - zero
      • | - or
      • [1-9]\d* - one to nine digit and then any zero or more digits
    • (?:[.,]\d*)? - an optional sequence of a comma or dot and then zero or more digits.
    • $ - end of string.