Reputation: 12675
From jquery.validate.js, this regex is used to validate a number. The problem is that it fails on .33 and passes on 0.33. I need to make it pass with, or without, the leading 0.
^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$
Upvotes: 3
Views: 222
Reputation: 729
This may be late but I have a better answer. Try this:
^-?((\d+)|([1-9]\d{0,2}(,\d{3})+)|(?=\.))(\.\d+)?$
Both the solutions by refp and solendil above will accept a number like 0,123,456 or 000,123 as valid. These are obviously not valid numbers.
This solution makes sure that the part before the first comma starts with a non-zero digit. It also takes care of the empty string issue that refp pointed out.
Upvotes: 0
Reputation: 104760
There are simpler ways to tell if a string refers to a number-
function isNumber(str){
return parseFloat(str)=== Number(str);
}
Upvotes: 1
Reputation: 63797
A positive lookahead such as (?=[.])
can be used to ensure that the strings either starts with a dot (.
) or follow the previously defined pattern.
^-?(?:(?=[.])|\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$
Upvotes: 2
Reputation: 8468
Try this
^-?(?:\d+|\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$
The extra question mark (spot it!) will make all the part before the decimal point optional.
Upvotes: 4