I am trying to write validation for a field, and a regex seems like the right solution. But I can't seem to get the syntax right. Here are the basic rules
- Must be positive
- Up to 3 digits before the decimal
- Up to 2 digits after the decimal
- Decimal is only present if there are numbers following it
- Not required to put a leading number before the decimal
This is what I came up with but it doesn't seem to be working, but I admit regex isn't my forte.
^[0-9]{0,3}?(\.)[0-9]{0,2}$|$ 13 Answers
Your ? placement is in the wrong place. {a,b}? will match the least amount possible between a and b. You probably want:
^([0-9]{0,3})(\.[0-9]{1,2})?$
^[0-9]{0,3}(\.[0-9]{1,2})?$
This one should do what you want.
use this regex :
^(\d{0,3}|\d{0,3}\.\d{1,2})$ this will work according to your requirement
3