Javascript does not have a built-in isNumeric function.
Instead a function must be implemented. In this article we shall
illustrate one method where we check the characters in the passed
string against a pre-defined list.
Two methods are used within the function charAt and indexOf.
The
charAt method is used to find out which character is in a
designated position within the string. The indexOf method is then
used to search theValidChars list of valid characters. If the character
doesn't exist in the list, if ValidChars.indexOf(Char) == -1, then an
invalid character is in the supplied string, sText, and the function is
aborted, returning false.
function IsNumeric(sText) {
var ValidChars = "0123456789.";
var Char;
for (i = 0; i < sText.length; i++) {
Char = sText.charAt(i);
if (ValidChars.indexOf(Char) == -1) {
return= false;
}
}
return IsNumber;
}
The
above function may also be used to check for a valid set of characters,
simply by changing the content of the string ValidChars. The following
function will also work, although perhaps a little less obviously.
function isNumeric(sText) {
return !/\D/sText
}
This
version of the function uses regular expresssions, it test to see
whether the string sText contains any non-numeric characters.
| This article viewed: 10368 times | Back |
Copyright © 2004-2007 Janet Systems Ltd.