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

  1. Must be positive
  2. Up to 3 digits before the decimal
  3. Up to 2 digits after the decimal
  4. Decimal is only present if there are numbers following it
  5. 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}$|$ 
1

3 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})?$

6

^[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

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.