Wednesday, October 28, 2009

JavaScript Numeric Validation

function IsNumeric(strString)
// check for valid numeric strings
{
var strValidChars = "0123456789.-";
var strChar;
var blnResult = true;

if (strString.length == 0) return false;

// test strString consists of valid characters listed above
for (i = 0; i < strString.length && blnResult == true; i++)
{
strChar = strString.charAt(i);
if (strValidChars.indexOf(strChar) == -1)
{
blnResult = false;
}
}
return blnResult;
}

Such a function can be used as follows to check a field and return an error message if the contents are not numeric:
if (document.frmUser.afield.value.length == 0)
{
alert("Please enter a value.");
}
else if (chkNumeric(document.frmUser.afield.value) == false)
{
alert("Please check - non numeric value!");
}

No comments:

Post a Comment