Wednesday, 17 October 2012

JavaScript Simple Form Validation | PHP Tutorials for Beginners


This tutorial shows the basic form validation using JavaScript. Form validation is one of the most common uses for JavaScript. JavaScript is a quick, easy way to check a user's input for mistakes, typos, and the omission of required fields. Because validation takes place on the client machine, there's no delay for contacting a remote server.

Name
Email
Pin Code
Country










In this example you have to create two different file, one for your form and other for the JavaScript validation code (Because we will include external js file.).

Step 1:- Create a simple html form by use of code provided below:

<html> 
<head>
    <title>JavaScript Form Validation</title>
    <script src = "javascript.js" language="javascript" type= "text/javascript"></script> 
  </head>
  <body>
    <form action="" name="Form" onsubmit="return(formvalidate());">
    <table cellspacing="2" cellpadding="2">
    <tr>
      <td align="right">Name</td>
      <td><input type="text" name="Name" /></td>
    </tr>
    <tr>
      <td align="right">Email</td>
      <td><input type="text" name="Email" /></td>
    </tr>
    <tr>
      <td align="right">Pin Code</td>
      <td><input type="text" name="Pin" /></td>
    </tr>
    <tr>
      <td align="right">Country</td>
    <td>
      <select name="Country">
<option value="" selected>Select Country</option>
<option value="1">USA</option>
<option value="2">JAPAN</option>
<option value="3">INDIA</option>
      </select>
    </td>
    </tr>
    <tr>
      <td align="right"></td>
      <td><input type="submit" value="Submit" /></td>
    </tr>
    </table>
    </form>
  </body>
<html>

Step 2:- Now create one Javascript.js file and put the below code inside that file.

function formvalidate()
{

   if( document.Form.Name.value == "" )
   {
     alert( "Please insert your name." );
     document.Form.Name.focus() ;
     return false;
   }
   if( !validateEmail())
   {
     alert( "Please insert your Email address." );
     document.Form.Email.focus() ;
     return false;
   }
   if( document.Form.Pin.value == "" ||isNaN( document.Form.Pin.value ) )
   {
     alert( "Please insert the pin code." );
     document.Form.Pin.focus() ;
     return false;
   }
   if( document.Form.Country.value == "" )
   {
     alert( "Please select your country!" );
     return false;
   }
   return( true );
}

function validateEmail()
{

   var emailID = document.Form.Email.value;
   atpos = emailID.indexOf("@");
   dotpos = emailID.lastIndexOf(".");
   if (atpos < 1 || ( dotpos - atpos < 2 )) 
   {
       
       return false;
   }
   return( true );
}


Your registration form with JavaScript validation is ready.

No comments:

Post a Comment