Reputation: 761
I need to validate currency values under $100, allowing the user to optionally leave out the decimal place. The dollar sign and comma are not needed (or allowed). Another validation component constrains the upper and lower values, so the regex expression only needs to validate 1 or 2 digits, with an optional decimal and 2 more digits.
These values would match:
10
5
5.00
10.00
These values would not match:
.25
10.1
10.255
What is the optimal regex pattern for this validation?
Upvotes: 0
Views: 96
Reputation: 26667
Something like
^\d{1,2}(\.\d{2})?$
^
Anchors the regex at the start of the string
d{1,2}
matches 1 or 2 digits \d
=> [0-9]
(\.\d{2})
matches .
followed by 2 digits
?
quantifier, quantifes the decimal part zero or one time
$
anchors the regex at the end of the string
Upvotes: 1