JavaScript isNumeric function
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:
// I use this function like this: if (isNumeric(myVar)) { }
// regular expression that validates a value is numeric
var 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;
}
Jake Munson
36 Yrs old
/^[-+]?[0-9]*\.?[0-9]+(?:[eE][-+]?[0-9]+)?\b/
Handles the end decimal and some other things :)
/^[-+]?[0-9]*\.?[0-9]+(?:[eE][-+]?[0-9]+)?$/
or
/^[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$/
if you prefer
Anyway, kudos on publishing this. I should have remembered it without looking it up.
I searched for it!
var result = x.match(RegExp);
//new
if (result==null) result=false;
//new
return result;
function isNumber( value )
{
return isFinite( (value * 1.0) );
}
function IsNumeric(n){if(n*1==n)return true;else return false;}
any non numeric value = NaN when multiplied by 1 thus altering the value of n
could use this too...
function IsNumeric(n){if(n*1==NaN)return false;else return true;}
with return result !== null;
with return result !== null; "
Wouldn't
return result || false;
also work?
isNaN(); // is NOT a number
If you want to alias the CF function then you could do this:
function isNumeric(value) {
return !isNaN(value);
}
Cheers,
Daniel Shaw
http://dshaw.com
function is_numeric(x) {
return (x!=null && !isNaN(x));
}
String.prototype.trim = function() {
return (this.replace(/^\s+/, '')).replace(/\s+$/, '');
};
String.prototype.isNumeric = function() {
return (this!=null && !isNaN(this) && this.trim()!="");
}
Number.prototype.isNumeric = function() {
return (this!=null && !isNaN(this));
}
// Can add isNumeric to other Constructors if you like.
Usage:
var a = " ";
var b = new Number();
var c = 5;
var d = new Number(); d=null;
a.isNumeric() //returns false
b.isNumeric() //returns true as defaults to 0
c.isNumeric() //returns true
d.isNumeric() //returns false
Regards
David Reabow
Are there any gotchas with isNaN(x) that I'm not seeing?
Putting a comma in there throws all of them off. Now if we talk comma's we could also talk how some cultures use periods but luckily my application is only targeting the states. I think I will stick with ^[-+]?(?:\d*|\d{1,3}(?:,\d{3})*)(?:\.\d+)?$ which lets me validate a wide range of cases.