To use this website fully, you first need to accept the use of cookies. By agreeing to the use of cookies you consent to the use of functional cookies. For more information read this page.

Form validation with JavaScript

Validation and it's importance

Validation normally takes place on both the client side and the server side, so it's important that JavaScript deals with this effectively. The simple reason for making it client side is that if validation takes place client side, the users hardware is the in charge of processing the validation input before it goes to the server, thus reducing load on the server since data which has not been tampered with can then be verified quickly (as it has made it to the server, the data has passed the validation stage on the local machine).

Validation is the method or system of validating an input. For instance, if a user is expected to enter a number between 1 and 100 and they enter 200, a validation error should occur, alerting the user to reinput the number.

Verification is different to validation. Verification should primarily be done server side and is out of the scope of this tutorial. Verification focuses on password checking, for instance comparing that the user's input password matches that on the database.

Validating using JavaScript

One of the most common ways to validate using JavaScript is to submit the form using JavaScript only when the form contains validated data.

Assume the following HTML code:

HTML
<form id="send_email" action="submit.php" method="post">
  <input id="email" name="email" />
  <button id="submit_btn" type="button">Submit</button>
</form>

In a normal situation, pressing the submit button would do nothing because it has the type="button" attribute and value pair. However, JavaScript can add custom functionality to this. Take a look at the following code:

JavaScript
var btn = document.getElementById('submit_btn');
btn.addEventListener('click', function(){
  //Do something
});

In the event listener some validation could be added so that it can check if it conforms to the validation tests:

JavaScript
var btn = document.getElementById('submit_btn');
btn.addEventListener('click', function(){
  //Validation
  var eml = document.getElementById('email');
  eml = eml.value;
  if(eml.indexOf("@") === -1){
    alert("Invalid email address");
  } else {
    document.getElementById('send_email').submit();
  }
});
Provide feedback on this page
Comments are sent via email to me.