In our previous tutorial, we learnt about simple validation of form, with conditions like required field, alpha numeric input only and specific. Now we will try other type of JavaScript validation. This article will cover different validation for most HTML elements. As described in our last article, validation can be done in two ways, “Server Side Validation” and “Client Side Validation”.

In this tutorial we will learn how to do client side validation. We will using JavaScript for it. We can do the validation using different logic of code.

Below are three way of JavaScript validation:

  • Each error will get alert message.
  • One alert box, where all the errors are displayed.
  • By displaying all error messages in HTML form element.

This is the HTML form we are going to use.

<body style="margin: 0 576px;">
	<div class="container" style="">
		<div class="user_form" style="width: 500px;height: 700px;">
			<fieldset>
			<legend>USER FORM</legend>
			<form action="#" method="post" onsubmit="return validation()">
				<div class="row" style="padding-bottom: 10px;">
					<div class="cols">Username</div>
					<div clas="cols"><input id="username" type="text" name="username"
						value=""></div>
				</div>
				<div class="row" style="padding-bottom: 10px;">
					<div class="cols">Password</div>
					<div class="cols"><input id="password" type="password" name="password"
						value=""></div>
				</div>
				<div class="row" style="padding-bottom: 10px;">
					<div class="cols">Confirm Password</div>
					<div class="cols"><input id="cpassword" type="password" name="cpassword"
						value=""></div>
				</div>
				<div class="row" style="padding-bottom: 10px;">
					<div class="cols">Name</div>
					<div class="cols"><input id="name" type="text" name="name"
						value=""></div>
				</div>
				<div class="row" style="padding-bottom: 10px;">
					<div class="cols">Country</div>
					<div class="cols">
						<select id="country" name="country">
							<option value="0">select-country</option>
							<option value="1">India</option>
							<option value="2">U.S.A</option>
							<option value="3">Australia</option>
							<option value="4">France</option>
						</select>	
					</div>
				</div>
				<div class="row" style="padding-bottom: 10px;">
					<div class="cols">Age</div>
					<div class="cols">
						<input type="text" name="age" id="age" value="">
					</div>
				</div>
				<div class="row" style="padding-bottom: 10px;">
		          <div class="cols">Subject</div>
		          <div class="cols">
		            <input type="checkbox" id="sub" name="sub" value="">Net
		            <input type="checkbox" id="sub" name="sub" value="">Php
		            <input type="checkbox" id="sub" name="sub" value="">Android
		            <input type="checkbox" id="sub" name="sub" value="">Java
		          </div>
		        </div>
		        <div class="row" style="padding-bottom: 10px;">
		          <div class="cols">Gender</div>
		          <div class="cols">
		            <input type="radio" id="gender" name="gender" value="0">Male
		            <input type="radio" id="gender" name="gender" value="1">Female
		          </div>
		        </div>
				<div class="row" style="padding-bottom: 10px;">
					<div class="cols">Email</div>
					<div class="cols"><input id="email" type="text" name="email"
						value=""></div>
				</div>
				<div class="row" style="padding-bottom: 10px;">
					<div class="cols">Contact Number</div>
					<div class="cols"><input id="contact" type="text" name="contact"
						value=""></div>
				</div>
				<div class="row">
					<div class="cols"><input type="submit" value="submit" name="submit"></div>
				</div>
			</form>
			</fieldset>
		</div>
	</div>
</body>
<script type="text/javascript">

function validation(){ var errorStatus = true;
<!-- validation code -->
}

 </script>

We have 10 form elements in above form. There are different HTML input type in above form. Start working by defining function on ‘onsubmit’ event. Return keyword is used when there is some specific process needed to be done, before form submission. Which means if a function returns true, only then the form should be submitted, else it will not submitted in case validation function have some error.

When user clicks on the submit button the function will be. After HTML ends, we give a script tag with the function. In the function, we set the ‘errorstatus’ variable status true to assume that there is error. Now, we can one by one put the validation code of all fields in the function.

Note: We can give the JavaScript validation using HTML Elements attribute like ID and/or NAME. In this example we have used both to implement the validation. To use this, we have to give ID and NAME in every form element. For example, we can give ID to country code input field as ‘ccode’ and country name input field as ‘cname’.

 Syntax for Getting form Element in JavaScript: 

document.getElementById('id');

document.getElementsByName('sub');

 

Method 1: JavaScript validation by alert. Each error message one by one for HTML form element for conditions “Required Field” And “Specific Value length”

Username Validation:

Aim of this validation is that the value of the username is not empty and length of characters is not greater than 10.

if(document.getElementById('username').value =="" ){

          alert("Please Enter Username");

          document.getElementById('username').focus();

          return false;

}else if(document.getElementById('username').value.length>10){

          alert("username should not be more than 10 characters");

          document.getElementById('username').focus();

          return false;

}

For username we gave two conditions, not empty and specific length. We checked if the value of the username is empty or not. If it is then the function will return false with alert message and if it is not than compiler will execute the next condition. In second condition we check the number of characters is greater than the user submitted input number (10 in this case) or not. If it is then that number function returns false with alert message otherwise next line of code will execute.

Password Validation:

We are going to validate that the value of the password is not empty and length of characters is greater than 6.

if(document.getElementById('password').value == ""){

          alert("Please Enter Password");

          document.getElementById('password').focus();

          return false;

}else if(document.getElementById('password').value.length<6){

          alert("password should be more than 6 characters");

          document.getElementById('password').focus();

          return false;

}

For password we doing same validations as username with same conditions. The empty field validation in which if the field is not empty than we move to next condition. In that we check the length of value is greater than given input number (6 in this case) or not. If it’s less than to that number the function returns false with the alert message, if true then it moves to next line of code.

Validation for “Confirm Password” match the value

JavaScript validation for confirm password:

We are going to validate if the value of password is not empty and matches with the password field.

if(document.getElementById('cpassword').value == ""){

          alert("Please Enter Confirm Password");

          document.getElementById('cpassword').focus();

          return false;

}else if(document.getElementById('cpassword').value != document.getElementById('password').value){

          alert("You Enter a Wrong Confirm Password");

          document.getElementById('cpassword').focus();

          return false;

}

In confirm password we check two conditions. One for not empty and second to confirm the value is same as the password field or not. For check an empty field we do the same as previous examples. We then give a condition to compare the values of password and confirm password. If it is not same, then the function returns false with the alert message otherwise its returns true.

Validation for ‘AlphaNumeric’ Value

Name validation for AlphaNumeric Value:

 The objective here is that the value of name should not empty, the value must be alphanumeric and the length of characters is not greater than 40.

if(document.getElementById('name').value !="")

  {

    var letterNumber = /^[0-9a-zA-Z]+$/;

    if(document.getElementById('name').value.match(letterNumber)) {

          if(document.getElementById('name').value.length>40){

                   alert("Name Should Not be More Than 40 characters");

                   document.getElementById('name').focus();

                   return false;

          }

    }else{

      alert("please enter only letters and numbers");

      document.getElementById('name').focus();

      return false;

    }

   }else{

    alert("Please Enter Name");

    document.getElementById('name').focus();

    return false;

  }

There are three conditions. First is for not empty which is same as above fields. Thereafter we check that the value is alpha numeric or not. For that we use regular expression of alphanumeric and store it in variable. Than we match the value of the user input to ‘name’ field with that variable. If it is not same then function returns false with the alert message otherwise we move to the next condition. The next condition is for length of value, which should not be greater than the specific number (40 here). If it’s greater than that then function returns false, else returns true.

JavaScript Validation Of required field On Selection Box

Country JavaScript validation for require field:

There must be one value selected on the selection box.

if(document.getElementById('country').value == 0){

          alert("Please Select Country");

          document.getElementById('country').focus();

          return false;

}

Generally for country we use a selection box in HTML. We set a value for each option of the selection box. Using that, we can give the validation on selection box. We do not have any country with 0 value, so we check that the value of a country is 0 or not. If the value is 0 than function returns false otherwise return true.

JavaScript validation for Get the Number from Specific Range

JavaScript Age Validation:

The age is not less than 18 or greater than 30.

if(document.getElementById('age').value!=""){

          if(document.getElementById('age').value<18 || document.getElementById('age').value>30){

                   alert('Your Age Should between 18 to 30');

                   document.getElementById('age').focus();

                   return false;

          }

}else{

          alert("Please Enter Your Age");

          document.getElementById('age').focus();

          return false;

}

In Age field we give an empty condition which is common and then we want a value which is between the two specific numbers (18 & 30). For that we give the condition if the value of age is less than 18 or greater than 30 the function returns false with the error message else it returns true.

JavaScript validation of required field on Checkbox & Radio Button

JavaScript validation for Subject checkbox:

There must be minimum one value checked on subject.

var subject=document.getElementsByName('sub');

if((subject[0].checked==false) && (subject[1].checked==false) && (subject[2].checked==false) && (subject[3].checked==false)){

          alert("Please Choose Your Subject");

          document.getElementById('sub').focus();

          return false;

}

In Subject we use a checkbox for understand a validation on it. We check the condition on array of the subject. We check that if value is false on each value means there is not checked in any value. The function returns false then with alert message otherwise returns false.

JavaScript validation for Gender:

There must be one value cheeked on gender.

var genders = document.getElementsByName("gender");

if((genders[0].checked==false) && (genders[1].checked==false)){

          alert("Please Select Your gender");

          document.getElementById('gender').focus();

          return false;

}

For gender we use a radio button element. The condition is same as the subject field. If there is no any value selected, then the function returns false with the alert message.

JavaScript Validation of valid Email:

 The validation field is required and must be in a valid format of email.

if(document.getElementById('email').value!=""){

          var regemail = /^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/;

          if(!document.getElementById('email').value.match(regemail)) {

                   alert("Please Enter Valid Email Address");

                   document.getElementById('email').focus();

                   return false;

          }

}else

          alert("Please Enter Your email");

          document.getElementById('email').focus();

          return false;

}

In email field we check for not empty and then we check the format of the email. We use regular expression of email for that. We store it in variable and then match it with the value of email field. If it is not matched with that format the function returns false with the error message otherwise it returns true.

JavaScript validation of Numeric Value:

Contact Number:

The contact number is required, value must be numeric and character length is 10 digits.

if(document.getElementById('contact').value!=""){

          var regphn = /^[0-9]*$/;

          if(document.getElementById('contact').value.match(regphn)){

                   if(document.getElementById('contact').value.length!=10){

                             alert('Contact Number Should be 10 digits');

                             document.getElementById('contact').focus();

                             return false;

                   }

          }else{

                   alert("Contact Number Should be numeric");

                   document.getElementById('contact').focus();

                   return false;

          }

}else{

          alert("Please Enter Your Contact Number");

          document.getElementById('contact').focus();

          return false;

}

In contact number we check three validation. First is for not empty, the second is for numeric and the third is for specific value length. After the not empty condition (same as above examples) we give a regular expression for numeric. If it is numeric than we come to the next condition which is for length of value. We check that the length of value is equal to 10 characters. If it is not 10 characters than the function returns false with the alert message.

In above example(s) we displayed error messages one by one in JavaScript alert popup box. That is one of the method to displaying error message in JavaScript. We now move on to two other methods to display error messages.

Method 2: Client side JavaScript validation by using one alert box to display all error messages

function validation(){

var errorStatus = true;
var errorMsg= "";
if(document.getElementById('username').value =="" ){
          errorMsg +="Please Enter Username\n";
}else if(document.getElementById('username').value.length>10){
          errorMsg +="username should not be more than 10 characters\n";
}

if(document.getElementById('password').value == ""){
          errorMsg +="Please Enter Password\n";
}else if(document.getElementById('password').value.length<6){
          errorMsg +="password should be more than 6 characters\n";
}

if(document.getElementById('cpassword').value == ""){
          errorMsg +="Please Enter Confirm Password\n";
}else if(document.getElementById('cpassword').value != document.getElementById('password').value){
          errorMsg +="You Enter a Wrong Confirm Password\n";
}

if(document.getElementById('name').value !="")
  {
    var letterNumber = /^[0-9a-zA-Z]+$/;
    if(document.getElementById('name').value.match(letterNumber)) {
          if(document.getElementById('name').value.length>40){
                   errorMsg +="Name Should Not be More Than 40 characters\n";
          }
    }else{
          errorMsg +="please enter only letters and numbers\n";
    }
   }else{
          errorMsg +="Please Enter Name\n";
  }

if(document.getElementById('country').value == 0){
          errorMsg +="Please Select Country\n";
}

if(document.getElementById('age').value!=""){
          if(document.getElementById('age').value<18 || document.getElementById('age').value>30){
                   errorMsg +="Your Age Should between 18 to 30\n";
          }
}else{
          errorMsg +="Please Enter Your Age\n";
}

var subject=document.getElementsByName('sub');
if((subject[0].checked==false) && (subject[1].checked==false) && (subject[2].checked==false) && (subject[3].checked==false)){
  errorMsg +="Please Choose Your Subject\n";
}

var genders = document.getElementsByName("gender");
if((genders[0].checked==false) && (genders[1].checked==false)){
  errorMsg +="Please Select Your gender\n";
}

if(document.getElementById('email').value!=""){
          var regemail = /^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/;
          if(!document.getElementById('email').value.match(regemail)) {
                   errorMsg +="Please Enter Valid Email Address\n";
         }
}else{
          errorMsg +="Please Enter Your email\n";
}

if(document.getElementById('contact').value!=""){
          var regphn = /^[0-9]*$/;
          if(document.getElementById('contact').value.match(regphn)){
                   if(document.getElementById('contact').value.length!=10){
                             errorMsg +="Contact Number Should be 10 digits\n";
                   }
          }else{
                   errorMsg +="Contact Number Should be numeric\n";
          }
}else{
          errorMsg +="Please Enter Your Contact Number\n";
}

if(errorMsg!=""){
    alert(errorMsg);
    return false;
  }else{
    return true;
  }
}

In this method we display all the error message in only one alert box. All the Fields and the all validation conditions are same as the previous method, just the message displaying method is different. We give one variable ‘errorMsg’ to contain all the messages. When the function returns false, we concat that message in the string of ‘errorMsg’ variable. Than we check if it is empty or not. If it is not empty we put that variable in alert and return false, which will display the alert box with all errors. If it is empty it returns true.

Method 3: JavaScript validation by displaying all error message in HTML form element

function validation(){

var errorStatus = true;
var errorMsg= "";
if(document.getElementById('username').value =="" ){
  errorMsg +="Please Enter Username"+"<br>";
}else if(document.getElementById('username').value.length>10){
  errorMsg +="username should not be more than 10 characters"+"<br>";
}

if(document.getElementById('password').value == ""){
  errorMsg +="Please Enter Password"+"<br>";
}else if(document.getElementById('password').value.length<6){
  errorMsg +="password should be more than 6 characters"+"<br>";
}

if(document.getElementById('cpassword').value == ""){
  errorMsg +="Please Enter Confirm Password"+"<br>";
}else if(document.getElementById('cpassword').value != document.getElementById('password').value){
  errorMsg +="You Enter a Wrong Confirm Password"+"<br>";
}

if(document.getElementById('name').value !="")
  {
    var letterNumber = /^[0-9a-zA-Z]+$/;
    if(document.getElementById('name').value.match(letterNumber)) {
      if(document.getElementById('name').value.length>40){
        errorMsg +="Name Should Not be More Than 40 characters"+"<br>";
      }
    }else{
      errorMsg +="please enter only letters and numbers"+"<br>";
    }
 }else{
    errorMsg +="Please Enter Name"+"<br>";
  }

if(document.getElementById('country').value == 0){
  errorMsg +="Please Select Country"+"<br>";
}

if(document.getElementById('age').value!=""){
  if(document.getElementById('age').value<18 || document.getElementById('age').value>30){
    errorMsg +="Your Age Should between 18 to 30"+"<br>";
  }
}else{
  errorMsg +="Please Enter Your Age"+"<br>";
}

var subject=document.getElementsByName('sub');
if((subject[0].checked==false) && (subject[1].checked==false) && (subject[2].checked==false) && (subject[3].checked==false)){
  errorMsg +="Please Choose Your Subject"+"<br>";
}

var genders = document.getElementsByName("gender");
if((genders[0].checked==false) && (genders[1].checked==false)){
  errorMsg +="Please Select Your gender"+"<br>";
}

if(document.getElementById('email').value!=""){
  var regemail = /^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/;
  if(!document.getElementById('email').value.match(regemail)) {
    errorMsg +="Please Enter Valid Email Address"+"<br>";
  }
}else{
  errorMsg +="Please Enter Your email"+"<br>";
}

if(document.getElementById('contact').value!=""){
  var regphn = /^[0-9]*$/;
  if(document.getElementById('contact').value.match(regphn)){
    if(document.getElementById('contact').value.length!=10){
      errorMsg +="Contact Number Should be 10 digits"+"<br>";
    }
  }else{
    errorMsg +="Contact Number Should be numeric"+"<br>";
  }
}else{
  errorMsg +="Please Enter Your Contact Number"+"<br>";
}

if(errorMsg!=""){
     document.getElementById('errormsg').innerHTML=errorMsg;
    return false;
  }else{
    return true;
  }
}

In this method, we display the all error message in top of the html form with the green font. The process is almost same as the previous method. We make a div and give it an id. As in previous method, if the ‘errorMsg’ is not empty than all error message will show in that div which id we give on, document.getElementById(‘errormsg’).innerHTML. If the condition is true than the function returns true.

 

That’s all folks. Hopefully this article will help you learn about JavaScript validation and how to implement it in HTML with different form element combination. Our next article will be about jQuery validation.

Have any question or query? Want to add more information for this article? Just comment below to share whats on your mind after reading this.
If you like our article, please share it with your friends who might find it helpful.