Validate Numeric Fields Using Javascript.
By Nannette Thacker - 1/18/2001
By Nannette Thacker - 1/18/2001
Use the onBlur() method to validate numeric fields with this checkNumeric() javascript function. Optionally pass in a period, comma, or hypen to indicate allowed values. Set the maximum and minimum value allowed.
If your allowed values always include period, comma, or hyphen, or never include those, you may easily edit the function to remove the parameter values from the onBlur() and function.
You may also use a variation of this routine to check for any combination of valid values. You don't have to use "0123456789" - you may instead use something else as your check string.
Here is the javascript:
<SCRIPT LANGUAGE="JavaScript"> <!-- Original: Nannette Thacker --> <!-- http://www.shiningstar.net --> <!-- Begin function checkNumeric(objName,minval, maxval,comma,period,hyphen) { var numberfield = objName; if (chkNumeric(objName,minval,maxval,comma,period,hyphen) == false) { numberfield.select(); numberfield.focus(); return false; } else { return true; } } function chkNumeric(objName,minval,maxval,comma,period,hyphen) { // only allow 0-9 be entered, plus any values passed // (can be in any order, and don't have to be comma, period, or hyphen) // if all numbers allow commas, periods, hyphens or whatever, // just hard code it here and take out the passed parameters var checkOK = "0123456789" + comma + period + hyphen; var checkStr = objName; var allValid = true; var decPoints = 0; var allNum = ""; for (i = 0; i < checkStr.value.length; i++) { ch = checkStr.value.charAt(i); for (j = 0; j < checkOK.length; j++) if (ch == checkOK.charAt(j)) break; if (j == checkOK.length) { allValid = false; break; } if (ch != ",") allNum += ch; } if (!allValid) { alertsay = "Please enter only these values \"" alertsay = alertsay + checkOK + "\" in the \"" + checkStr.name + "\" field." alert(alertsay); return (false); } // set the minimum and maximum var chkVal = allNum; var prsVal = parseInt(allNum); if (chkVal != "" && !(prsVal >= minval && prsVal <= maxval)) { alertsay = "Please enter a value greater than or " alertsay = alertsay + "equal to \"" + minval + "\" and less than or " alertsay = alertsay + "equal to \"" + maxval + "\" in the \"" + checkStr.name + "\" field." alert(alertsay); return (false); } } // End --> </script> |
Here is the HTML:
<form method="POST" id=myform name=myform action="/articles/articles/javascript/checkNumeric.asp?ID=<%=siteID%>"> Allow Comma, Period, Negative <input type=text onBlur="checkNumeric(this,-5,5000,',','.','-');" name='allowcomma' size=10 maxlength=10><br> No Comma, Period, Negative <input type=text onBlur="checkNumeric(this,5,60,'','','');" name='nocomma' size=10 maxlength=10><br> <input type="Submit" name="Save" value="Save"> </form> |