value
on input
elements is always a string. It might be a string of digits.
If you want to know whether that string only contains valid numbers, you have to parse it (and decide what you consider a valid number, and allow for that).
For instance, you'll get people telling you to use parseInt(myVar)
or the unary +
(+myVar
) or isNaN(myVar)
(which does what the unary +
does) or Number(myVar)
(same), but:
parseInt
only parses the beginning of the string, parseInt("345foo")
is 345
parseInt
is, of course, only for whole numbers; you'd want parseFloat
for numbers with fractional portions
All of those will fail to understand thousands separators
All of those will fail to understand a decimal separator that isn't .
(e.g., in many locales it's ,
or sometimes even a space)
+myVar
and Number(myVar)
and isNaN(myVar)
and such will treat an empty string as 0
...that kind of thing. So you have to do some prep on the string according to what input you want to accept.
Once you've decide what format(s) to handle, there are a dozen questions with answers here about doing the actual parsing: