3

I've come up with this regular expression to validate a number which can have Maximum length-13 (including decimal points),Maximum no of decimal points-3,Maximum length of a whole number-12.

^(\d{1,12}([.]\d{1,1})?|\d{1,11}([.]\d{1,2})?|\d{1,10}([.]\d{1,3})?)$

Could anyone tell me if my approach is correct or give me a better solution?

4
  • 1
    Your regex matches 123456789012.3 which is a total of 14, but you said "number which can have Maximum length-13 (including decimal points)"... so... it has 12 whole dec. numbers but .3 are extras... Commented Oct 15, 2016 at 4:56
  • Can you have a 0 digit fractional part? i.e. Would 0. be valid? Commented Oct 15, 2016 at 5:08
  • Just in case, if this is an input you can use type="number" in your markup instead of playing with regexes :) Commented Oct 15, 2016 at 5:34
  • I'm sorry, did not count '.'. So excluding dot length should be 13 including decimal places . 123456789012.3 is fine. Commented Oct 15, 2016 at 14:12

1 Answer 1

3

This would also work:

^(?=.{1,13}$)(\d{1,12})(\.\d{1,3})?$

Uses positive look ahead to match the entire string length is ok. Then it uses a group to match from 1 - 12 digits Then there's an optional group to match a decimal followed by 1-3 digits.

Edited: Simplified since the rules don't allow a 13 digit integer-part

Sign up to request clarification or add additional context in comments.

3 Comments

Amazing and bulletproof.
@RokoC.Buljan Thanks. Wouldn't have been so simple if you hadn't pointed out the "no 13 digit integer part" issue
Thanks Tibrogargan. Considering '.' , I guess it should be ^(?=.{1,14}$)(\d{1,12})(\.\d{1,3})?$.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.