Reputation: 6932
I've come up with this regular expression to validate a javascript number according to the specification:
(-|\+|)(\d+\.?\d*|\.\d+)([eE](-|\+|)\d+)?
As far as I can think of, these are valid numbers in js:
123,123.3, .3, -123, -.3, -.3e-2, -.3e+2, +.2e2... and so forth.
I've been trying to find a verified regular expression on the internet so that I could compare my solution but to no avail.
Could anyone tell me if my approach is correct or give me a better solution?
Upvotes: 1
Views: 111
Reputation: 627468
While using isNan
is the correct way of checking numbers in JavaScript, you can also validate floating point numbers with [-+]?[0-9]*\.?[0-9]+(?:[eE][-+]?[0-9]+)?
regex (taken from Regular-Expressions.info).
Consider using appropriate anchors though! (^
for string start, $
for string end).
Upvotes: 1