Loading, please wait...

Form Validation

Form Validation

 In HTML document, forms contain certain fields which are mandatory to be filled and in a correct manner. So, in the normal way when the user entered the data in the forms then the form transferred to the server side in order to get checked, if the entered data is incorrect then the server pass the whole data back to the user to fill the correct one. So, it consumes a lot of time

 

So, to overcome this problem the form must be checked on the client side which the help of validation process.

The form element has a onsubmit event which is used in order to perform validation.

It can prevent the user from leaving blank fields or entering too little or too much data in the fields.

 

So, Validation is defined as the process which checks that the data supplied by the user should be correct and must be in defined criteria before submitting the form.

 

Code:

 

Basic Form

<html>
<head>
<script>
</script>
</head>
<body>
<h1> Contact Form</h1>
<form  name="BasicForm" onsubmit="return(validation());">
<p>Name: <input type="text"  name="Name"> </p><br>     
<p>E-mail:  <input type="text"  name="EMail">  </p><br>
<p>Password: <input type="text"  name="Password"> </p><br>
<p>Country:  
<select name="Country">
<option>India</option>
<option>China</option>
<option>USA</option>
<option>Australia</option>
</select>
</p>
<input type="submit" value="Submit" name="Submit"> 
</form>
</body>
</html>

 

 

Validation

<script>
function validation()
{
var name=document.BasicForm.Name;
if( name.value == "" )
{
  alert( "Please Enter the name!" );
  name.focus() ;
  return false;
}
var email = document.BasicForm.EMail.value;
atpos = email.indexOf("@");
dotpos = email.lastIndexOf(".");

if (atpos < 1 || ( dotpos - atpos < 2 ))
{
alert("Please enter correct email ID")
document.BasicForm.EMail.focus() ;
return false;
}

var password=document.BasicForm.Password;
if (password.value == "" || isNaN( password.value ))                      
{
      window.alert("Please enter your password");
      password.focus();
      return false;
}

var country=document.BasicForm.Country;
if(country.value == "Default")
   {
       alert('Select any country from the list');
       country.focus();
       return false;
   }
 }
</script>

 

Output:

If we don't enter the values in a specified field, according to the specified criteria then it shows a popup message in order to command the user to enter the correct data in a specified criteria.