You are on page 1of 3

JavaScript Form Validation

JavaScript Form Validation


JavaScript can be used to validate 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 re!uired fields empty"
has the user entered a valid e#mail address"
has the user entered a valid date"
has the user entered te$t in a numeric field"
%e!uired Fields
The function belo& checks if a re!uired field has been left empty. 'f the re!uired field is blank( an
alert bo$ alerts a message and the function returns false. 'f a value is entered( the function returns
true )means that data is *+,
function validate_required(field,alerttxt)
{
with (field)
{
if (value==null||value=="")
{
alert(alerttxt);return false;
}
else
{
return true;
}
}
}
The entire script( &ith the HTML form could look something like this
<html
<head
<scri!t t"!e="text#$avascri!t"
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,"%mail must &e filled out'")==false)
{email(focus();return false;}
}
}
<#scri!t
<#head
<&od"
<form action="su&mit(htm" onsu&mit="return validate_form(this)"
method="!ost"
%mail) <in!ut t"!e="text" name="email" si*e="+,"
<in!ut t"!e="su&mit" value="-u&mit"
<#form
<#&od"
<#html
-#mail Validation
The function belo& checks if the content has the general synta$ of an email.
This means that the input data must contain at least an . sign and a dot ).,. /lso( 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)
{
a!os=value(index.f("/");
dot!os=value(last0ndex.f("(");
if (a!os<1||dot!os2a!os<3)
{alert(alerttxt);return false;}
else {return true;}
}
}
The entire script( &ith the HTML form could look something like this
<html
<head
<scri!t t"!e="text#$avascri!t"
function validate_email(field,alerttxt)
{
with (field)
{
a!os=value(index.f("/");
dot!os=value(last0ndex.f("(");
if (a!os<1||dot!os2a!os<3)
{alert(alerttxt);return false;}
else {return true;}
}
}
function validate_form(thisform)
{
with (thisform)
{
if (validate_email(email,"4ot a valid e2mail address'")==false)
{email(focus();return false;}
}
}
<#scri!t
<#head
<&od"
<form action="su&mit(htm" onsu&mit="return validate_form(this);"
method="!ost"
%mail) <in!ut t"!e="text" name="email" si*e="+,"
<in!ut t"!e="su&mit" value="-u&mit"
<#form
<#&od"
<#html