Rin Minase
Rin Minase

Reputation: 338

Regular Expression with 2 Decimal Places or Whole numbers and a Range

I want to validate pH Levels in my input with a digit and with only one or two decimal places, or just with a digit.

My regex expression contains some errors in it (input can reach 100):

/^([0-9]|1[0-4])+(\.[0-9][0-9]?)?$/

pH ranges only from 1.00 to 14.00. values in the range (1-14) with .0 or .00 (e.g. 3.00 and 4.0) are also considered valid

Valid values

1, 1.0, 1.00, 2.3, 2.12, 2.54, 13.22, 13.99

Invalid values

0, 0.99, 14.01, 1.123

Upvotes: 1

Views: 4729

Answers (2)

Amilcar Zambrano
Amilcar Zambrano

Reputation: 21

That expression was testing from 0.00 until 16.00 and it worked good, be carefull to that take exactly two point decimal or it will not match

^(([1-9]|1[0-3])\.\d\d)|(14\.00)$

Upvotes: 0

dana
dana

Reputation: 18135

/^(([1-9]|1[0-3])(\.\d\d?)?|14(\.00?)?)$/

https://regex101.com/r/B9eKXN/1

In particular, look at the unit tests which all seem to be passing.

Upvotes: 3

Related Questions