skip to Main Content

For angular app,
We need validation like the user can enter between 0-99 and also can enter up to 2 digit decimal points.

For example,

  • 0 -> Pass

  • 0.1 -> Pass

  • 1.12 -> pass

  • 12.12 -> Pass

  • 100 -> Fail

  • 19.111 -> Fail

  • 1.-> Fail

^[0-9]+([.][0-9]{1,2})?$ this pattern is working for other cases apart from case( 100 -> Fail)

for that I tried pattern something like ^([0-9]{1,2})+([.][0-9]{1,2})?$ but it’s not working as expected.

Please suggest a pattern that covers all cases.

3

Answers


  1. Chosen as BEST ANSWER

    Made the below pattern with the help of wnvko and Sameshostee answers, it's working properly with this Validators.pattern('...').

    Thanks @wnvko and @Sameshostee for your help.

    ^(?:99|[0-9]{1,2})([.][0-9]{1,2})?$


  2. /^(?:99|d{1,2})(?:.d{1,2})?$/

    • ^ – beginning of string
    • (?:99|d{1,2}) – non-capturing group, 0-99
    • (?:.d{1,2})? – optional non-capturing group (.# or .##)
    • $ – end of string

    That should be it, please test it further.

    Login or Signup to reply.
  3. You can go with something like this

    /^(?:[1-9][0-9]?|0)(?:.[0-9]{1,2})?$/
    

    Here’s how it works:

    • ^ matches the start of the string.
    • (?:[1-9][0-9]?|0) matches any number between 0 and 99
    • (?:.[0-9]{1,2})? matches up to two digits after the decimal point
    • $ matches the end of the string

    This will not match 09

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search