< Javascript Tutorial

Javascript form validation

← Previous Next →


 It is important to validate the form submitted by the user because it can have inappropriate values. So validation is must.

The JavaScript provides you the facility the validate the form on the client side so processing will be fast than server-side validation. So, most of the web developers prefer JavaScript form validation.

Through JavaScript, we can validate name, password, email, date, mobile number etc fields.

JavaScript form validation example

In this example, we are going to validate the name and password. The name can’t be empty and password can’t be less than 6 characters long.

Here, we are validating the form on form submit. The user will not be forwarded to the next page until given values are correct.

<script>
    function validateform(){  
    var name=document.myform.name.value;  
    var password=document.myform.password.value;  
      
    if (name==null || name==""){  
      alert("Name can't be blank");  
      return false;  
    }else if(password.length<6){  
      alert("Password must be at least 6 characters long.");  
      return false;  
      }  
    }  
</script>

<body>
    <form name="myform" method="post" action="abc.jsp" onsubmit="return validateform()" >
       Name: <input type="text" name="name">
       Password: <input type="password" name="password">
       <input type="submit" value="register">
    </form>
</body>

JavaScript Retype Password Validation

<script type="text/javascript"> 
function matchpass(){  
    var firstpassword=document.f1.password.value;  
    var secondpassword=document.f1.password2.value;  
      
    if(firstpassword==secondpassword){  
    return true;  
    }  
    else{  
    alert("password must be same!");  
    return false;  
    }  
}  
</script>
 
<form name="f1" action="register.jsp" onsubmit="return matchpass()">
  Password:<input type="password" name="password" />
  Re-enter Password:<input type="password" name="password2"/>
  <input type="submit">
</form>

JavaScript Number Validation

Let's validate the textfield for numeric value only. Here, we are using isNaN() function.

<script> 
function validate(){  
    var num=document.myform.num.value;  
    if (isNaN(num)){  
      document.getElementById("numloc").innerHTML="Enter Numeric value only";  
      return false;  
    }else{  
      return true;  
    }  
}  
</script>
  
<form name="myform" onsubmit="return validate()" >
  Number: <input type="text" name="num">
  <input type="submit" value="submit">
</form>
← Previous Next →