1

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?

Link to test my solution

6
  • 3
    I don't get it, what's wrong with isNaN ? Commented Apr 3, 2015 at 21:18
  • it's a regular expression not intended to be used in js Commented Apr 3, 2015 at 21:19
  • And yet, you seem to be trying to match valid numbers in js ? Commented Apr 3, 2015 at 21:19
  • no, that's not the point. The point is I want to figure out a regular expression that could validate a js number Commented Apr 3, 2015 at 21:20
  • @acontell what's the end goal of validating js-valid numbers? Commented Apr 3, 2015 at 21:21

1 Answer 1

1

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).

Demo is available here.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.