What I want to do is determine if a string is numeric. I would like to know what people think about the two solutions I am trying to decide between (OR if there is a better solution that I have not found yet). The parseInt function is not suitable because it will return an integer value for a parameter like "40 years old". The two solutions I am deciding between are:
Use Integer.valueOf() with try catch
function isNumeric(quantity)
{
var isNumeric = true
try
{
Integer.valueOf(quantity)
}
catch(err)
{
isNumeric = false
}
return isNumeric
}
Or check each character individually
function IsNumeric(quantity)
{
var validChars = "0123456789";
var isNumber = true;
var nextChar;
for (i = 0; i < quantity.length && isNumber == true; i++)
{
nexChar = quantity.charAt(i);
if (validChars.indexOf(nextChar) == -1)
{
isNumber = false;
}
}
return IsNumber;
}
I would have thought there would be a simpler solution than both of these though. Have I just missed something?
NOTE: I am using jQuery aswel so if there is a jQuery solution that that would be sufficient