JavaScript isNumeric function

  • Post author:
  • Post category:Uncategorized

The other day I needed to check a value to make sure it’s numeric, using JavaScript (it was an Ajax app). I poked around online and a few sites said that JS doesn’t have such a function. I also found a few sites that offered an isNumeric function, but most of them didn’t check for decimals and/or negatives. So I created my own using a Regular Expression:function isNumeric(x) { // I use this function like this: if (isNumeric(myVar)) { } // regular expression that validates a value is numericvar RegExp = /^(-)?(\d*)(\.?)(\d*)$/; // Note: this WILL allow a number that ends in a decimal: -452. // compare the argument to the RegEx // the 'match' function returns 0 if the value didn't match var result = x.match(RegExp); return result;}