JavaScript Form Validation

The JavaScript provides the facility to validate the form data on the client-side, so the processing will be faster in the server-side. With JavaScript we can validate various form filed's data like name, password, email, date, mobile number etc.

Name Validation :
<html>
<body>
  <form method="post" name="myform" action="" onsubmit="return validateform()">
    Enter Your Name : <input type="text" name="name"/>
    <input type="submit" value="Submit"/>
  </form>
  <p id="demo"></p>
  <script>
    function validateform() {
      var msg = document.getElementById("demo");
      var name = document.myform.name.value;
      if(name == null || name == "") {
        msg.innerHTML = "Please Enter Your Name ?"; 
        return false;
      } else {
        return true;
      }
    }
  </script>
</body>
</html>

Password Validation :
<html>
<body>
  <form method="post" name="myform" action="" onsubmit="return validateform()">
    Enter Password : <input type="password" name="password1"/><br/>
    Enter Password Again : <input type="password" name="password2"/><br/>
    <input type="submit" value="Submit"/>
  </form>
  <p id="demo"></p>
  <script>
    function validateform() {
      var msg = document.getElementById("demo");
      var pass1 = document.myform.password1.value;
      var pass2 = document.myform.password2.value;
      if(pass1 == null || pass1 == "") {
        msg.innerHTML = "Please Enter Your Password ?"; 
        return false;
      } else if(pass2 == null || pass2 == "") {
        msg.innerHTML = "Please Enter Password Again ?";  
        return false;
      } else if(pass1.length<6 || pass2.length<6) {
        msg.innerHTML = "The password length is at least 6 ?";  
        return false;
      } else if(pass1 != pass2) {
        msg.innerHTML = "The password must be same in both box ?";  
        return false;
      } else {
        return true;
      }
    }
  </script>
</body>
</html>

Number Validation :
<html>
<body>
  <form method="post" name="myform" action="" onsubmit="return validateform()">
    Enter 10 digit Phone Number
    <input type="text" name="phnumb"/>
    <input type="submit" value="Submit"/>
  </form>
  <p id="demo"></p>
  <script>
    function validateform() {
      var msg = document.getElementById("demo");
      var phn = document.myform.phnumb.value;
      if(phn.length < 10){
        msg.innerHTML = "Number is Less than 10 digits.";
        return false;
      } else if(phn.length > 10) {
        msg.innerHTML = "Number is greater than 10 digits.";
        return false;
      } else if(isNaN(phn)) {
        msg.innerHTML = "Not a number.";
        return false;                    
      } else {
        return true;
      }
    }
  </script>
</body>
</html>

Next Topic :