There will be a case where you have to limit the HTML form inputs to integers or decimals, so that invalid character entries can be prevented. The following tutorial and code can be used to validate a text box and allow only numeric data including decimal.
Place the following code in the head section of the html page.<script language="JavaScript">
function fn_validateNumeric(thi,dec)
{
if (((event.keyCode < 48) || (event.keyCode > 57)) && (event.keyCode != 46))
event.returnValue = false;
if(dec=="n" && event.keyCode == 46)
{
event.returnValue = false;
}
else
{
if(event.keyCode == 46 && instr(thi.value,".")>=0)
event.returnValue = false;
}
}</script>
Place the below code inside the html form or just copy the highlighted text and place it in your text box code:Syntax: To allow only integers<input ONKEYPRESS="fn_validateNumeric(this,'n')" name="txt_numeric" type="text" id="txt_numeric" size="10" maxlength="10">
Syntax: To allow integers & decimals<input ONKEYPRESS="fn_validateNumeric(this,'')" name="txt_numeric" type="text" id="txt_numeric" size="10" maxlength="10">
The above code requires the
Javascript InStr function
So, whenever a key is pressed when the focus is in the text box, the function will be called and validated. The function will not allow any characters other than the numeric data(including decimal). If you dont want the decimal, just remove the keycode condition which checks for 46 and the second if statement)