JavaScript Form Validation

As you know that you can validate any HTML form just by using the onsubmit attribute of the FORM element.

The onsubmit invokes a function, which is create by using JavaScript to check whether the field of the form is valid or not valid.

JavaScript Required Fields Validation

Using JavaScript, you are free to restrict a user to fill up the form fields. Here is an example shows how to validate required fields using JavaScript:

<!DOCTYPE HTML>
<HEAD>
<TITLE>JavaScript Required Fields Validation</TITLE>
<SCRIPT type="text/javascript">
   function validateRequiredFields(this_form)
   {
      var username=this_form.usrname.value;
      var password=this_form.usrpassword.value;
      if(username==null || username=="")
      {
         alert("Please enter your username");
         this_form.usrname.focus();
         return false;
      }
      if(password==null || password=="")
      {
         alert("Please enter your password");
         this_form.usrpassword.focus();
         return false;
      }
      return true;
   }
</SCRIPT>
</HEAD>
<BODY>

<FORM action="#" onsubmit="return validateRequiredFields(this)" method="Post">
   Username: <input type= "text" name="usrname"/><span style="color:red;">*</span><br/>
   Password: <input type= "password" name="usrpassword"/><span style="color:red;">*</span><br/>
   <INPUT type="submit" value="Login"/>
</FORM>

</BODY>
</HTML>

Here is the sample output produced by the above JavaScript required field form validation example program. This is the initial output:

javascript form validation

Without entering the username and the password, just click on the Login button, then you will watch the following output:

javascript form validation example

Now enter your username as shown in the following snapshot:

javascript form validatation program

After entering the username, leave the password field and click on the Login button, then you will watch this output:

javascript required field validatation

Here is the live demo output of the above JavaScript required field form validation example program.

Username: *
Password: *

JavaScript Numbers Validation

You can use a JavaScript function named isNaN to validate a number object. Here is an example shows how to validate numbers using JavaScript:

<!DOCTYPE HTML>
<HTML>
<HEAD>
   <TITLE>JavaScript Number Validation</TITLE>
   <SCRIPT type="text/javascript">
   function validateNumber(this_form2)
   {   
      var num2 = this_form2.num2.value;
      if(num2==null|| num2=="")
      {
         alert("Please enter a number.");
         this_form2.num2.focus();
         return false;
      }
      if(isNaN(num2))
      {
         alert("It is not a valid number.");
         this_form2.num2.focus();
         return false;
      }   
      return true;   
   }
   </SCRIPT>
</HEAD>
<BODY>

<FORM action="#" onsubmit="return validateNumber(this)" method="Post">
   Enter a Number: <INPUT type="text" name="num2"/><BR/>
   <INPUT type="submit" value="Validate"/>
</FORM>

</BODY>
</HTML>

Here are some sample outputs of the above JavaScript number validation example program. This is the initial output:

javascript number validation

Now here is the output produced when you click on the Validate button without entering any number:

javascript number validation example

And here is the output produced when you enter a character except of number and click on the Validate button:

validate numbers using javascript

Here is the live demo output of the above number validation example using JavaScript:

Enter a Number:

JavaScript Username and Password Validation

You can also validate username and password field using JavaScript such as to check the values of the fields for null and blank or to restrict the length of the values and many more. Here is an example shows how to validate username and password field of the form using JavaScript:

<!DOCTYPE HTML>
<HTML>
<HEAD>
   <TITLE>JavaScript Username and Password Validation</TITLE>
   <SCRIPT type="text/javascript">
   function validateUsernamePassword(this_form3)
   {
      var userName = this_form3.user_name.value;
      var pass1 = this_form3.password1.value;
      var pass2 = this_form3.password2.value;
      if(userName=="")
      {
         alert("Please enter your username.");   
         this_form3.user_name.focus();
         return false;
      }
      if(userName.length<6)
      {
         alert("Username must be at least of 6 characters.");   
         this_form3.user_name.focus();
         return false;
      }
      if(pass1=="")
      {
         alert("Please enter your password.");   
         this_form3.password1.focus();
         return false;
      }
      if(pass1.length<8)
      {
         alert("Password must contain at least of 8 digits");   
         this_form3.password1.focus();
         return false;
      }
      if(pass2=="")
      {
         alert("Please re-enter your password for confirmation.");   
         this_form3.password2.focus();
         return false;
      }
      if(pass1.length>=8 && pass2.length>=8 )
      {
         if(pass1!=pass2)
         {
               alert("Sorry! Password mismatched! Please try again.");   
               return false;
         }
      }   
      return true;
   }
   </SCRIPT>
</HEAD>

<BODY>
<FORM action="#" onsubmit="return validateUsernamePassword(this)" method="Post">
   Enter Username: <INPUT type="text" name="user_name"/><BR/>
   Enter Password: <INPUT type="password" name="password1"/><BR/>
   Re-enter Password: <INPUT type="password" name="password2"/><BR/>
   <INPUT type="submit" value="Login"/>
</FORM>

</BODY>
</HTML>

Here are some sample outputs produced by the above JavaScript username and password field validation example program. This is the initial output:

javascript username password validation

Now click on the Login button without entering anything. Then you will watch the following output:

javascript username password field validation

Now enter the username (contains only of 5 characters) and click on the Login button. Then you will watch the following output:

validate username password using javascript

Now enter fresherearth as username and codes as password, press on the Login button. Then here is the output you will watch:

javascript username password validating program

Now enter fresherearth as username, 123456789 as password, 123456780 as re-enter password, and click on the Login button. Then here is the output produced by the above username and password validation program using JavaScript:

validate form using javascript

Here is the live demo output produced by the above JavaScript username and password example program.

Enter Username:
Enter Password:
Re-enter Password:

JavaScript Phone Number Validation

You can also validate the Phone number entered by the user using JavaScript. To validate phone number, you have to check the following three conditions:

Here is an example shows how to validate phone number entered by the user using JavaScript:

<!DOCTYPE HTML>
<HTML>
<HEAD>
   <TITLE>JavaScript Phone Number Validation</TITLE>
   <SCRIPT type="text/javascript">
   function validatePhoneNumber(this_form4)
   {
      var phon=this_form4.phonnumbe.value;
      if(phon==null||phon=="")
      {
         alert("Please enter your phone number.");
         this_form4.phonnumbe.focus();   
         return false;
      }
      if(phon.length<10)
      {
         alert("Phone number must be at least of 10 digits.");
         this_form4.phonnumbe.focus();   
         return false;
      }
      if(isNaN(phon))
      {
         alert("Sorry! You have entered an invalid phone number! Please try again.");
         this_form4.phonnumbe.focus();   
         return false;
      }
      return true;
   }
   </SCRIPT>
</HEAD>
<BODY>

<FORM action="#" onsubmit="return validatePhoneNumber(this)" method="Post">
   Phone Number: <input type="text" name="phonnumbe"/><BR/>
   <INPUT type="submit" value="Validate"/>
</FORM>

</BODY>
</HTML>

Here is the sample outputs produced by the above JavaScript phone number validation example program. This is the initial output:

javascript phone number validation

Now press on the Validate button without entering anything. Here is the output you will watch:

javascript phone number validating program

Now enter fresherearth as phone number and click on the Validate button, you will watch the following output:

validate phone number using javascript

Here is the live demo output produced by the above phone number validation example program using JavaScript:

Phone Number:

JavaScript Time Validation

You can also validate time using JavaScript. In other word, you can check whether the entered time is in correct format or not using JavaScript. Here is an example shows how to validate time using JavaScript.

<!DOCTYPE HTML>
<HTML>
<HEAD>
   <TITLE>JavaScript Time Validation</TITLE>
   <SCRIPT type="text/javascript">
   function validateTime(this_form5)
   {
      var timeVa = this_form5.timeval.value;
      if(timeVa == "")
      {      
         alert("Please enter the Time.");
         this_form5.timeval.focus();
         return false;
      }
      var positio = timeVa.indexOf(":");
      if(positio<0)
      {
         alert("Sorry! You have entered an invalid Time! The colon ( : ) is missing between HH and MM.");
         this_form5.timeval.focus();
         return false;
      }
      if(positio>2 || positio<1)
      {
         alert("Sorry! You have entered an invalid Time! The Time format should be HH:MM AM/PM.");
         this_form5.timeval.focus();
         return false;
      }
      var hours = timeVa.substring(0, positio);   
      if(hours>12)
      {
         alert("Sorry! You have entered an invalid Time! Hours cannot be greater than 12.");
         this_form5.timeval.focus();
         return false;
      }
      if(hours<=0)
      {
         alert("Sorry! You have entered an invalid Time! Hours cannot be smallar than 0.");
         this_form5.timeval.focus();
         return false;
      }
      var min = timeVa.substring(positio+1, positio+3);   
      if(min>59)
      {
         alert("Sorry! You have entered an invalid Time! Mins cannot be greater than 59.");
         this_form5.timeval.focus();
         return false;
      }
      if(min<0)
      {
         alert("Sorry! You have entered an invalid Time! Mins cannot be smallar than 0.");
         this_form5.timeval.focus();
         return false;
      }
      var t1  = timeVa.substring(5,8);   
      if(t1!= "AM" && t1!= "am" && t1!="PM" && t1!= "pm")
      {
         alert("Sorry! You have entered an invalid Time! Time should be end with AM or PM.");
         this_form5.timeval.focus();
         return false;
      }
      return true;   
   }
   </SCRIPT>
</HEAD>

<BODY>
<FORM action="#" onsubmit="return validateTime(this)" method="Post">
   Enter Time (HH:MM AM/PM): <input type="text" name="timeval"/><br/>
   <INPUT type="submit" value="Validate"/>
</FORM>

</BODY>
</HTML>

Here are some sample outputs produced by the above JavaScript time validation example program. This is the initial output:

javascript time validation

Now enter 10 12AM and click on the Validate button. You will watch the following output:

validate time using javascript

Here is the live demo output produced by the above time validation program using JavaScript.

Enter Time (HH:MM AM/PM):

JavaScript Date Validation

You can also validate date entered by the user using JavaScript. You can validate date depends on the format such as mm/dd/yyyy format. In this format you have to validate according to the mm/dd/yyyy format that means the month and date should have exactly of 2 digits and the year should have four digits and at last all the three (day, month, and year) must be separated by the / symbol.

Here is an example demonstrates how to validate date entered by the user using JavaScript:

<!DOCTYPE HTML>
<HTML>
<HEAD>
   <TITLE>JavaScript Date Validation</TITLE>
   <SCRIPT type="text/javascript">
   function isDate(dateTxtVal)
   {
      var objecDate;  
      var mSeconds;    
      if (dateTxtVal=="")  
      {
         alert("Please enter the Date."); 
         return false;
      }
      var dayVal   = dateTxtVal.substring(3,5);
      var monthVal = dateTxtVal.substring(0,2)-1; 
      var yearVal  = dateTxtVal.substring(6,10);
      if (dateTxtVal.substring(2,3) != '/')
      {
         alert("Sorry! You entered the Date in wrong format! Please enter the date in correct format.");
         return false;
      }
      if (dateTxtVal.substring(5,6) != '/')
      {
         alert("Sorry! You entered the Date in wrong format! Please enter the date in correct format.");
         return false;  
      }
      mSeconds = (new Date(yearVal, monthVal, dayVal)).getTime();
      objecDate = new Date();
      objecDate.setTime(mSeconds);   
      if (objecDate.getDate()!= dayVal) 
      {
         alert("Sorry! You have entered the wrong Day! Please try again.");    
         return false;
      }
      if (objecDate.getMonth()!= monthVal) 
      {
         alert("Sorry! You have entered the wrong month! Please try again.");  
         return false;
      }
      if (objecDate.getFullYear()!= yearVal) 
      {
         alert("Sorry! You have entered the wrong year! Please try again.");  
         return false;
      }
      return true;   
   }
   function validateDate(thisform)
   {
      var dateTxtVal = thisform.dateVa.value;
      if (isDate(dateTxtVal)) 
         return true;
      else  
         return false;
   }
   </SCRIPT>
</HEAD>
<BODY>

<FORM action="#" onsubmit="return validateDate(this)" method="Post">
   Enter Date (mm/dd/yyyy): <INPUT type="text" name="dateVa"/><BR/>
   <INPUT type="submit" value="Validate"/>
</FORM>

</BODY>
</HTML>

Here are some sample outputs produced by the above JavaScript date validation example program. This is the initial output:

javascript date validation

Now enter 10:05:2015 and click on the Validate button. Then you will watch the following output:

validate date using javascript

Here is the live demo output produced by the above date validation example using JavaScript.

Enter Date (mm/dd/yyyy):

JavaScript Form Validation More Examples

Here are some simple example program, shows how to validate form using JavaScript:

<!DOCTYPE html>
<html>
<head>
   <title>JavaScript Form Validation Example</title>
   <script>
   function validateFormFun()
   {
      var x = document.forms["formNumberOne"]["firstName"].value;
      if (x == null || x == "")
      {
         alert("Please enter your name first.");
         return false;
      }
   }
   </script>
</head>
<body>

<form name="formNumberOne" action="#" onsubmit="return validateFormFun()" method="post">
   Name: <input type="text" name="firstName">
   <input type="submit" value="Validate">
</form>

</body>
</html>

Here is the live demo output produced by the form validation example using JavaScript:

Name:

Here is another example, demonstrates JavaScript form validation. In this example, if an input field contains invalid data, displays an error message:

<!DOCTYPE html>
<html>
<head>
   <title>JavaScript Form Validation Example</title>
   <script>
   function validateFormFun2()
   {
      var inputObject = document.getElementById("inputId2");
      if (inputObject.checkValidity() == false)
      {
         document.getElementById("paragraph2").innerHTML = inputObject.validationMessage;
      }
      else
      {
         document.getElementById("paragraph2").innerHTML = "It is OK";
      }
   }
   </script>
</head>
<body>

<p>Enter your marks out of 100.</p>
<input id="inputId2" type="number" min="0" max="100">
<button onclick="validateFormFun2()">Submit</button>
<p>If entered mark is less than 0 or greater than 100 then an error message will be displayed below.</p>
<p id="paragraph2"></p>

</body>
</html>

Here is the live demo output produced by the above form validation example using JavaScript:

Enter your marks out of 100.

If entered mark is less than 0 or greater than 100 then an error message will be displayed below.

JavaScript Online Test


« Previous Tutorial Next Tutorial »