JavaScript Validations

As you have learned already about the JavaScript Form Validation. Now let's take a look at the following example, helps you to understand the process of validation:

<html>
<head>
   <title>JavaScript Validations</title>
   <script type="text/javascript">
      <!--
      // JavaScript validation code will come here
      //-->
   </script>
</head>

<body>
<form action="test.php" name="JavaScriptValidation" onsubmit="return(validateFun());">
   <table cellspacing="2" cellpadding="2" border="1">
   <tr>
      <td align="right">Name</td>
      <td><input type="text" name="username" /></td>
   </tr>
   <tr>
      <td align="right">EMail</td>
      <td><input type="text" name="useremail" /></td>
   </tr>
   <tr>
      <td align="right">Zip Code</td>
      <td><input type="text" name="userzip" /></td>
   </tr>
   <tr>
      <td align="right">Country</td>
      <td>
      <select name="usercountry">
         <option value="-1" selected>[choose]</option>
         <option value="1">INDIA</option>
         <option value="2">USA</option>
         <option value="3">UK</option>
         <option value="4">CANADA</option>
      </select>
      </td>
   </tr>
   <tr>
      <td align="right"></td>
      <td><input type="submit" value="Submit" /></td>
   </tr>
   </table>
</form>

</body>
</html>

Now, here we are going to create a JavaScript validation code to validate the input data. Here is the implementation of the function validate():

<script type="text/javascript">
   function validateFun()
   {
      if(document.JavaScriptValidation.username.value == "")
      {
         alert("Name must be entered.");
         document.JavaScriptValidation.username.focus();
         return false;
      }
      if(document.JavaScriptValidation.useremail.value == "")
      {
         alert("EMail must be entered.");
         document.JavaScriptValidation.useremail.focus();
         return false;
      }
      if(document.JavaScriptValidation.userzip.value == "" || isNaN(document.JavaScriptValidation.userzip.value) || document.JavaScriptValidation.userzip.value.length != 5)
      {
         alert("Zip must be provided in the form #####");
         document.JavaScriptValidation.userzip.focus() ;
         return false;
      }
      if(document.JavaScriptValidation.usercountry.value == "-1")
      {
         alert("Country must be selected.");
         return false;
      }
      return(true);
   }
</script>

JavaScript Online Test


« Previous Tutorial Next Tutorial »