I'am trying to get regex which can validate accepted numbers between 0 to 20 and these numbers can followed by an optional decmial point, followed by one or two digits. and not allow special characters it should be accept :

1 true
2 true
2.5 true
.
.
15,25 true
16.369 false
16++++ false
16,32-+* false
20 true

I tried this but it accept 16,25++++

 var regex = /^(?:1?\d(?:\.\d{1,2})?|20(?:\.0?0?)?)$/

1 Answers

1
The fourth bird On Best Solutions

You could use:

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

Explanation

  • ^ Start of string
  • (?: Non capturing group
    • (?:\d|1[0-9]) Match 0-9 or 10 - 19
    • (?:[,.]\d{1,2})? Match optional part to match a decimal and 1-2 digits
    • | Or
    • 20(?:[,.]0{1,2})? Match 20 with an optional part to match a decimal and 1-2 zeroes
  • ) Close non capturing group
  • $ End of string

Regex demo