Validate decimal numbers in Javascript

8

What is the simplest and most correct way to validate a decimal number in Javascript?

For example, how to implement a IsNumeric function that has the following Test Cases:

IsNumeric('-1')     true
IsNumeric('-1.5')   true
IsNumeric('0')      true
IsNumeric('0.42')   true
IsNumeric('.42')    true
IsNumeric('99,999') false
IsNumeric('0x89f')  false
IsNumeric('#abcdef')false
IsNumeric('1.2.3')  false
IsNumeric('')       false
IsNumeric('blah')   false
    
asked by anonymous 05.06.2014 / 04:28

1 answer

10

I believe it would be through the use of a regular expression. An expression that satisfies all your proposed tests would be:

^-?\d*\.?\d+$

Example in jsFiddle . Explaining:

  • ^ start of string
  • -? with or without forward
  • \d* zero or more digits (so that .42 validates, it is important to accept zero digits before the point)
  • \.? with or without dot
  • \d+ one or more digits
  • $ end of string

Other expressions could be used if you wanted to accept a larger range of numbers - such as grouping thousands using the comma (American standard), permitting scientific notation using e (common in programming languages), allowing% in front of only one less, etc. And an "obvious" problem with the proposed expression is that it does not reject numbers with leading zeros.

In the end, it's a matter of accurately identifying what format a string might be expected to have to be considered "numeric" and adjusting the expression accordingly. It may become a bit large, but in my opinion this is still simpler than trying a parse manual (only if what you consider "number" does not fit into a regular language is that a more sophisticated method becomes necessary.)

    
05.06.2014 / 06:36