19 Years of Excellence 99% Hiring Rate

An Easy Tutorial on HTML Form Validation Using JavaScript

ADMEC Multimedia Institute > Web Design > An Easy Tutorial on HTML Form Validation Using JavaScript

Hi, I am Abhishek Ranjan a web designer working in a company in Delhi and studying UI development and responsive website designing in this institute to excel my knowledge of JavaScript, jQuery, and Bootstrap to the advanced level.

What is Form Validation?

Form validation is the process of checking that a form has been filled in correctly before it is processed, this is called form validation.

What You Need to Know before From Validation?

  • HTML
  • CSS
  • JavaScript

Note:- If you don’t have knowledge of HTML, CSS & JavaScript than you may face some difficulties in validating a HTML form yet I will make all the step very easy to understand by you.

Let’s start form validation in JavaScript

There are main two methods of validating form:

  • Server side method
  • Client side method

Server-side: This validation is more secure but often more tricky to code because it takes down the performance of the website. It is compulsory to add in a web form but along with the client side validation. It is important when a hacker disables the JavaScript then server side validation protects your website.

Client-side: It is done by JavaScript. This validation is easier to do and quicker too (the browser doesn’t have to connect to the server to validate the form, so the user finds out instantly if they’ve missed out that required field!).

JavaScript, provides a way to validate form’s data on the client’s computer before sending it to the web server. Form validation generally performs two functions.

  • Basic Validation – First of all, the form must be checked to make sure data was entered into each form field that required it. This would need just 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. This would need to put more logic to test correctness of data.

Lets start the Validation of an HTML Form using JavaScript

Let’s build a simple form with a validation script. The form will include more than one input box, select-box, checkbox, radio-button, drop-down-box, message-box, reset-button and a submit button. Our validation script will ensure that the users enter their proper information before the form is sent to the server.

There are two procedure two validate a form using JavaScript:

  1. Simple JavaScript
  2. Object Oriented JavaScript (OOJS)

Validating an HTML form using OOJS is out of the scope of this article. We will surely write on that soon.

Example:

HTML form:

First we need to create a form using HTML and CSS (only for presentation purposes). If you are not good in HTML, I would recommend you our Advanced HTML5 and CSS3 Course.

Below I used few attributes in first line inside <form> tag e.g. method, action, onsubmit=”return validation(this) in HTML first line which is necessary for Form:

Ok now,

First telling you what is a method?

Method is the action that can be performed on objects through which a browser accomplishes some useful tasks such as validation response, security, and sends form information to the server.

There are two types of methods: –

  • Post
  • Get

Post method: Post method is used for sending information to server. All programmers use mainly post method because it is secure and can transfer unlimited information.

Get method: Get method is used for sending information to server too. Get method is less-secure than Post method.

Action: Action is an form attribute where we assign a PHP file generally and this file capture the data submitted from this form and then validate it for the further uses.

onsubmit: onsubmit is an event of JavaScript, it monitors for the submit action. As someone clicks on

<form method="post" action="https://www.admecindia.co.in" onsubmit="return validation(this)">
     Name:<input type="text" name="name" />
     Phone:<input type="text" name="phone" />
     Email:<input type="text" name="email" />
     Gender:
     <input type="radio" value="male" name="gender" >Male
     <input type="radio" value="female" name="gender" >Female
     Reference:
     <input type="checkbox" value="tv" name="tv" >TV     
     <input type="checkbox" value="radio" name="radio" >Radio
     Course:
     <select name="course">
          <option value="">Select Please</option>
          <option value="Graphic">Graphic</option>
          <option value="Web">Web</option>
          <option value="Animation">Animation</option>
     </select>
     Comments: <textarea rows="5" cols="10" name="comm"></textarea>
     <input type="submit" value="Submit">
     <input type="reset" value="Reset">
</form>

Lets Write JavaScript Required to Validate above HTML Form

I am going to create a function with the name of validation and it has a parameter in it. This parameter will be replace with ‘this’ keyword in form’s ‘onsubmit’ attribute so it will point to the form. I will be collecting all the values first and then add conditions to check one by one using ‘if’ conditional so that I can show all the errors at a time. You will notice a regular expression pattern too in this form validation in JavaScript code.

<script type="text/javascript">
  //lets create a function
  function validation(arg){
     // arg is used to pass value

     var gName = arg.name.value;
     //Get the value of name(selecter) and put in gName(variable)

     var gPhone = arg.phone.value;
     //Get the value of phone(selecter) and put in gPhone(Variable)

     var gEmail = arg.email.value;
     //Get the value of email(selecter) and put in gEmail(Variable)

     var gComm = arg.comm.value;
     //Get the Value of comm(selecter) and put in gComm (Variable)

     //lets create a Regular Expression or RegExp pattern to validate our email address value coming from a form field.
     var ePat = /^[a-z-._0-9]+@[a-z0-9]+\.[a-z.]{2,5}$/;

     //Find a single character, except newline or line terminator
     var namePatDt = /\./;

     //Only digits find
     var namePatDgt = /\d/;

     // err variable is used to show error message.
     var err = "";

     // errNum variable is used to show error index
     var errNum = 0;

     if (gName == "" || gName.length < 3 || namePatDt.test(gName) || namePatDgt.test(gName)) {
          errNum++;
          err += errNum + ". Invalid name.\n";
     }
     /*  The above code checks the value : If Value empety  or value length less than 3 or  value is digit than Show error Indvalid Name  */

     if (gPhone == "" || gPhone.length < 8 || isNaN(gPhone)) {
          errNum++;
          err += errNum + ". Invalid phone num.\n";
     }
     /* This code check the value : If value is empty or value length less than 8 or is not a null then show error Invalid Phone num */

     if (gEmail == "") {
          errNum++;
          err += errNum + ". Enter Email.\n";
     }
     /* If you don't Enter anything in Email field than show error(Enter Email)  */
     else{
          if(!ePat.test(gEmail)){
               errNum++;
               err += errNum + ". Invalid Email.\n";
          }
     }
     /*  If you don't Enter Email address in ePat format (i already discribe "ePat") than shaw error (Invalid Email)  */

     if (gComm == "") {
          errNum++;
          err += errNum + ". Enter comments.\n";
     }
     /* If you don't Enter anything in Comment field than show error(Enter Comments) */

     if (!arg.gender[0].checked && !arg.gender[1].checked) {
          errNum++;
          err += errNum + ". Select gender.\n";
     }
     /* If you don't  checked 0 index of gender field  or 1 index than show error(Select gender)*/

     if (!arg.tv.checked && !arg.radio.checked) {
          errNum++;
          err += errNum + ". Select Reference.\n";
     }
     /*  If you don't  checked tv field and radio field than show error(Select Reference) */

     if (arg.course.selectedIndex < 1) {
          errNum++;
          err += errNum + ". Select Course.\n";
     }
     /*  This code check your selection index if your index is less than 1 than show error (Select course) */

     if (errNum>0) {
          alert(err);
          return false;
     }
     /*  If errNum is greater than 0 than alert error and return "false" */
     else{
          alert('done');
          return true;
     }
     /* If errNum is less than 0 or 0 than alert "done" and return "true"*/
  }

    main();
</script>

Summary

Above explanation will surely help you in understanding Form Validation in JavaScript and HTML. The Form Validation is being used almost in every website. It is very good to create a safe and performance rich website because everything can’t be left out for the server as sever sucks. If you want any help or advanced Form Validation training using JavaScript then you can join online or classroom JavaScript classes.

Related Posts

Leave a Reply

Talk to Us