Entry
How can I check whether a text field contains a number or not?
How can I check whether a string contains a valid number?
How can I check whether a string contains a valid number?
Mar 21st, 2000 07:46
Martin Honnen,
JavaScript 1.1+ (so every browser besides NN2 and IE3) has the top
level function
isNaN
for that (it is also allegedly around in JavaScript 1.0 on unix but I
can't check that).
So if you try
isNaN('1.3')
it will return
false
but
isNaN('Kibo')
returns
true
That should suffice for elementary form field checking.
There is also
parseInt
and
parseFloat
but both check the beginning of a string for a valid integer/float and
discard the rest of the string so while
isNaN('1.3Kibo')
returns
true
the expression
parseFloat('1.3Kibo')
returns
1.3
So parseInt/parseFloat are good for conversion but of limited use for
number format checking.
Of course with JavaScript 1.2 the power of regular expressions is at
your hands to do sophisticated pattern checks. For instance to check
that a string contains nothing but digits
var nonDigit = /\D/g;
if (nonDigit.test('123'))
// contains something else that a digit
else
// contains only digits