Form validation is used to occur on the server, the client has entered all the necessary data, and then presses the Submit button. If the data of some of the clients that have been entered is either in the wrong form or simply lost, the server sends all the necessary data back to the client and requests the form to be resubmitted with the correct information. This is a lengthy process that will increase the burden on the server.
JavaScript, provides a way to authenticate data in the form of a client's computer before it is sent to the Web server. Form validation is usually done in two ways.
- Basic validation-First of all, the table must be checked to ensure that the data entered requires each of its form fields. This will pass through each field of the table just to loop and examine the data.
- Data format Validation-second, the data entered must check the correct format and value. This will require placing more logic to test the correctness of the data.
We will give an example to understand the validation process. The following is a simple form:
Basic Form Validation:
First, we'll show you how to do a basic form validation. The above table requires the Validate () function to verify that the data occurred in the OnSubmit event. The following is the implementation of the Validate () function:
<script type= "Text/javascript" >
<!--
//Form validation code would come here.
function Validate ()
{
if (Document.myForm.Name.value = = "")
{
alert ("Please provide your name!");
Document.myForm.Name.focus ();
return false;
}
if (Document.myForm.EMail.value = = "")
{
alert ("Please provide your email!");
Document.myForm.EMail.focus ();
return false;
}
if (Document.myForm.Zip.value = = "" | |
isNaN (document.myForm.Zip.value) | |
Document.myForm.Zip.value.length!= 5)
{
alert ("Please provide a Zip in the format #####.");
Document.myForm.Zip.focus ();
return false;
}
if (Document.myForm.Country.value = = "-1")
{
alert ("Please provide your country!");
return false;
}
return (TRUE);
}
-->
</script>
data Format validation:
Now we'll see how we can validate the form data we entered before we submit it to the Web server.
This example shows how to validate the input e-mail address, which means that the e-mail address must contain at least one @ symbol and one point (.). Also, @ must not be the first character of an e-mail address, and the last point has to be one character following the @ sign:
<script type= "Text/javascript" >
<!--
function Validateemail ()
{
var emailid = Document.myForm.EMail.value;
Atpos = Emailid.indexof ("@");
Dotpos = Emailid.lastindexof (".");
if (Atpos < 1 | | (Dotpos-atpos < 2))
{
alert ("Please enter correct email ID")
Document.myForm.EMail.focus ();
return false;
}
return (TRUE);
}
-->
</script>