JavaScript can be used to validate input data in HTML forms before sending
off the content to a server.
JavaScript Form Validation
JavaScript can be used to validate input data in HTML forms before sending off
the content to a server.
Form data that typically are checked by a JavaScript could be:
* has the user left required fields empty?
* has the user entered a valid e-mail address?
* has the user entered a valid date?
* has the user entered text in a numeric field?
Required Fields
The function below checks if a required field has been left empty. If the
required field is blank, an alert box alerts a message and the function returns
false. If a value is entered, the function returns true (means that data is OK):
function validate_required(field,alerttxt)
{
with (field)
{
if (value==null||value=="")
{
alert(alerttxt);return false;
}
else
{
return true;
}
}
}
The entire script, with the HTML form could look something like this:
<script type="text/javascript">
function validate_required(field,alerttxt)
{
with (field)
{
if (value==null||value=="")
{
alert(alerttxt);return false;
}
else
{
return
true
}
}
}
function validate_form(thisform)
{
with (thisform)
{
if (validate_required(email,"Email must be filled out!")==false)
{
email.focus();return false;
}
}
}
</script>
<form action="submitpage.htm" onsubmit="return validate_form(this)"
method="post">
Email: <input style="background-color: rgb(255, 255, 160);" name="email"
size="30" type="text">
<input value="Submit" type="submit">
</form>
E-mail Validation
The function below checks if the content has the general syntax of an email.
This means that the input data must contain at least an @ sign and a dot (.).
Also, the @ must not be the first character of the email address, and the last
dot must at least be one character after the @ sign:
function validate_email(field,alerttxt)
{
with (field)
{
apos=value.indexOf("@");
dotpos=value.lastIndexOf(".");
if (apos<1||dotpos-apos<2) type="text/javascript"></script>
function validate_email(field,alerttxt)
{
with (field)
{
apos=value.indexOf("@");
dotpos=value.lastIndexOf(".");
if (apos<1||dotpos-apos<2)>
<form action="submitpage.htm" onsubmit="return validate_form(this);"
method="post">
Email: <input style="background-color: rgb(255, 255, 160);" name="email"
size="30" type="text">
<input value="Submit" type="submit">
</form>