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?
You can remove some redundant parenthesis:
And something like
(( ... )+)?can be replaced by:( ... )*, so the final regex might look like this:And if you’d like to reject input like:
and only allow for:
Then do something like this: