JavaScript Form Validation

What is form validation?

  • Form validation is the process of checking the forms that have been filled in correctly before they are processed.
  • It provides a method to check the user entered information on client-side before the data is submitted to the server-side.
  • It includes two methods for validating forms:
    1. Server-Side (ASP, PHP)
    2. Client-Side (JavaScript)
  • It displays alerts for incorrect data entered by the user.
  • Client-side validation is faster than Server-side validation.

Example : Simple Form Validation Program

validation.html          //File name

<html>
<body>
     <script>  
     function validateemail()  
     {  
          var a = document.myform.email.value;  
          var atposition = a.indexOf("@");  
          var dotposition = a.lastIndexOf(".");  
          if (atposition<1 || dotposition<atposition+2 || dotposition+2>=a.length)
          {  
               alert("Please Enter a valid E-mail Id");  
               return false;  
          }  
     }  
     </script>  
</body>
<body>
     <form name="myform"  method="post" action="validpage.html" onsubmit="return validateemail();">  
          Enter Your Email Id: <input type="text" name="email"><br/>  
          <input type="submit" value="Submit">  
     </form>  
</body>
</html>

validpage.html          //File name

<html>
     <body>
     <script type="text/javascript">
          alert("You are a Valid User !!!");
     </script>
     </body>
</html>


Output:
validate form 1

validate form 2