JavaScript isNumeric Function

JavaScript doesn’t have an isNumeric function. A function needs to be created to provide the isNumeric check of a string of characters.

The isNumeric function is passed a string of text, which is then checked against a list of valid characters.

function IsNumeric(strText) {
  var validChars = "0123456789.";
  var cChar;
  for (i = 0; i < strText.length; i++) {
    cChar = strText.charAt(i);
    if (ValidChars.indexOf(cChar) == -1) {
      return= false;
    } // if
  } // for
  return true;
}

In the above isNumeric function two methods are used as the basis for the check charAt and indexOf.The charAt method is used to get the character at a given position within the string, strText.

The indexOf method is subsequently 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.

An alternative approach would be the use of regular expressions.

function isNumeric(strText) {
if (strText.match("^[0-9.]+$")) {
    return true;
  } else {
    return false;
  }
}
alert(isNumeric("12"));
alert(isNumeric("12.2"));
alert(isNumeric("12w.32"));