Cover all the javascript validations in one html form

Javascript validation code

First of all, the form must be checked to make sure all the mandatory fields are filled in. It would require just a loop through each field in the form and check for data. Data Format Validation − Secondly, the data that is entered must be checked for correct form and value.

In this example, we are going to validate the name, email, password, confirm password and gender etc. Here we will cover all the html control like text box, select box, radio button and file upload.

Example

We will take an example to understand the process of validation. Here is a simple form in html format.

<!DOCTYPE html>
<html>
<head>
<title>How to validate HTML registration form by using javascript</title>
</head>
<body>
<div class="container">
  <h4>Registration Form</h4>
  <form name="registration" method="post" action="https://shinerweb.com/" enctype="multipart/form-data" >
    <table>
      <tr>
        <td><label for="name">Name:</label></td>
        <td><input type="text" name="name" id="name" placeholder="Enter your name"></td>
      </tr>
      <tr>
        <td><label for="email">Email:</label></td>
        <td><input type="text" name="email" id="email" placeholder="Enter your email"></td>
      </tr>
      <tr>
        <td><label for="password">Password:</label></td>
        <td><input type="password" name="password" id="password" placeholder="Enter your password"></td>
      </tr>
	  <tr>
        <td><label for="conf_password">Confirm Password:</label></td>
        <td><input type="password" name="conf_password" id="conf_password" placeholder="Enter your confirm password"></td>
      </tr>
      <tr>
        <td><label for="phoneNumber">Phone Number:</label></td>
        <td><input type="number" name="phoneNumber" id="phoneNumber"></td>
      </tr>
      <tr>
        <td><label for="gender">Gender:</label></td>
        <td>Male: <input type="radio" name="gender" id="gender1" value="male">
          Female: <input type="radio" name="gender" id="gender2"value="female"></td>
      </tr>
      <tr>
        <td><label for="language">language</label></td>
        <td>
          <select name="language" id="language">
            <option value="">Select language</option>
            <option value="English">English</option>
            <option value="Spanish">Spanish</option>
            <option value="Hindi">Hindi</option>
            <option value="Arabic">Arabic</option>
            <option value="Russian">Russian</option>
          </select>
        </td>
      </tr>
      <tr>
        <td><label for="zipcode">Attachement:</label></td>
        <td><input type="file" name="attachement" id="attachement"></td>
      </tr>
     
      <tr>
        <td colspan="2"><input type="submit" class="submit" onclick="formValidation();return false;" value="Register" /></td>
      </tr>
    </table>
  </form>
</div>
</body>

<script type = "text/javascript">
         <!--
            // Form validation code will come here.
         //-->
</script>
</html>

Output

Javascript validation form

Form Validation

First let us see how to do a form validation. In the above form, we are calling formValidation() to validate data when onsubmit event is occurring. The following code shows the implementation of this formValidation() function.

<script type = "text/javascript">
// function for form varification
function formValidation() {
  
	var name = document.getElementById("name").value;
	var email = document.getElementById("email").value;
	var password = document.getElementById("password").value;
	var conf_password = document.getElementById("conf_password").value;
	var phoneNumber = document.getElementById("phoneNumber").value;
	var language = document.getElementById("language").value;
	var attachement = document.getElementById("attachement").value;
	
	if(name=='')
	{
	alert("Please enter your name!");
	document.getElementById("name").focus(); //for set focus
	return false;
	}
	// checking name length
	if (name.length < 2 || name.length > 20) {
	alert("Name length should be more than 2 and less than 21");
	document.getElementById("name").focus(); //for set focus
	return false;
	}
	
	if(email=='')
	{
	alert("Please enter an email!");
	document.getElementById("email").focus(); //for set focus
	return false;
	}
	// checking email format
	var mailformat = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	if(!mailformat.test(email))
	{
	alert("Please enter a valid email!");
	document.getElementById("email").focus(); //for set focus
	return false;
	} 
	
	if(password=='')
	{
	alert("Please enter password!");
	document.getElementById("password").focus(); //for set focus
	return false;
	}
	if(conf_password=='')
	{
	alert("Please enter confirm password!");
	document.getElementById("conf_password").focus(); //for set focus
	return false;
	}
	
	//check password and confirm password is match
	if(password!=conf_password)
	{
	alert("Password and confirm password does not match.");
	document.getElementById("password").focus(); //for set focus
	return false;
	} 
  
	// checking phone number
	if (!phoneNumber.match(/^[1-9][0-9]{9}$/)) {
	alert("Phone number must be 10 characters long number and first digit can't be 0!");
	document.getElementById("phoneNumber").focus(); //for set focus
	return false;
	}
	
	//checking gender selected or not
	if(document.getElementById('gender1').checked || document.getElementById('gender2').checked) {
	} else {
	alert ("You must select a gender.");
	return false;
	}
  
	// checking language
	if (language === "") {
	alert("Please select your language!")
	return false;
	}
	
	if(attachement=="")
	{
			alert("Please select the attachement file.");
			return false;
	}
	else
	{
		//set extension validation
		var re = /(\.zip)$/i;		
		if(!re.exec(attachement) && attachement != '' )
		{
			alert("Please upload zip file.");
			return false;
		}
		//set file size validation
		var oFile = document.getElementById("attachement").files[0]; 
		if (oFile.size > 10485760) // 10 MiB for bytes.
		{
			alert("File size must under 10MB.");
			return;
		}
	}
 document.registration.submit();
  return true;
}
</script>

Once you setup above javascript code then your all validations working. For more details please see the output.

Related Posts

Divyesh Patel

I'm Divyesh Patel, Web & App developer. I want to make things that make a difference. With every line of code, i strive to make the web a beautiful place.

Leave a Reply