Number Validation in Forms

by Hiroshi on June 15, 2008

in Form, Form Validation

Following script will check that whether user has entered the number or digit in field. e.g. In Phone Number Text Field.

Head Section Code

Use this script in head section of webpage or call an external javascript file with this code.

<script language="javascript">
function CheckData()
{
with(document.send)
{
if (mobile.value == "")
{
alert("Please enter a value for the \"numbers\" field.");
mobile.focus();
mobile.value="";
return (false);
}
// only allow numbers to be entered
 
var checkOK = "0123456789";
var checkStr = mobile.value;
var allValid = true;
var allNum = "";
for (i = 0; i < checkStr.length; i++)
{
ch = checkStr.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)
{
alert("Please enter only digit characters in the \"numbers\" field.");
mobile.focus();
mobile.value="";
return (false);
}
}
return true;
}
</script>

Form Code

<form name=send action="msn.com" method="post" id="mobile" onSubmit="return CheckData()">
<input name="mobile" type="text" id="mobile" />
<input type="submit" name="Submit" value="Submit" />
</form>

Download Number Validation or Authentication Script

Related Posts

Previous post:

Next post: