How can I simply this number format validation regex?

So, I have this if statement:
if (String(val).search(/^((\d+(((\,\d{3,})+)?)(\.\d+)?)|(\.\d+))$/) !== -1)

Which says (as far as I am aware):
The string must either start with at least one digit, or a ..
If the string starts with a digit there can optionally be commas in the string, as long as the commas are followed by at least three digits. If the string has a . in it, it must be followed by at least one digit.
There can be only one .

So, strings like:

5
5.00
5000
5,000
5000.00
5,000.00

Will all return true

But strings that contain anything but 0-9 , . or are malformed will return false. so strings like this:

5,00
5,00.00
5.00.00
a5

Now, the above works, but I am wondering if there is any way to simplify it?

Answers:

Answer

You can remove some redundant parenthesis:

^(\d+((\,\d{3,})+)?(\.\d+)?|\.\d+)$

And something like (( ... )+)? can be replaced by: ( ... )*, so the final regex might look like this:

^(\d+(\,\d{3,})*(\.\d+)?|\.\d+)$

And if you'd like to reject input like:

50000,000,000.0

and only allow for:

5,000,000.0
50,000,000.0
500,000,000.0

Then do something like this:

^(\d{1,3}(\,\d{3})*(\.\d+)?|\.\d+)$
Answer

I don't think you could simplify it, beyond stripping out a few parens, and as it is it's arguably not complex enough. The pattern will also allow malformed strings such as

50000,000,000.000000000

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.