Form Validation Using JavaScript

This tutorial discusses how to create a JavaScript-enabled form that checks if there is any vacant section which user have to fill up before it is sent to server. This process is called form validation.


Form validation is the process to check weather the user have given all the necessary important information before it is processed. For example in a registration form if the user hadn’t fill up his e-mail then you can check it using form handler.
There are two main form validation methods.
1. Server side scripting : it is normally difficult to code and done using CGI script , asp, etc.
2. Client side scripting : this is done by javascript and relatively easy.

We achive validation in javascript by invoking validate_form() function. Next we are going to create a registration form where after submission the data that typically will be checked by a JavaScript are:

1. Required value
2. Valid user name
3. Valid password
4. Valid e-mail address

HTML Form:

The scripts explained letter are structured on this HTML form. The user clicks the submit button on the form and the form is send to javascript validation function for checking. The HTML form is as follows.

<!DOCTYPE html>
<h1>Form Validation</h1>
<form name="demo" onsubmit="return validateFormOnSubmit(this)">
    <td><label for="username">User Name:</label></td>
    <td><input name="username" type="text"></td>
    <td><label for="pwd">User Password</label></td>
    <td><input name="pwd"  type="password"></td>
    <td><label for="email">user E-mail:</label></td>
    <td><input name="email"  type="text"></td>
    <td><label for="phone">User Contact No: </label></td>
    <td><input name="cntct"  type="text"></td>
        <label for="from">User Address</label></td>
    <td><input name="from"  type="text"></td>
  <input type="radio" name="gender" value="male" />Male
  <input type="radio" name="gender" value="female" />Female
    <td> </td>
    <td><input name="Submit" value="submit" type="submit" ></td>
    <td> </td>
<title>JavaScript Tutorial</title>

In the above we can see that it is a plain HTML coded form. Next we will learn the validation scripting of the form and its contents.


This is a main function that calls a series of sub functions, each of which checks a single form element for compliance. If the element complies then sub function returns an empty string. Otherwise it returns a message describing the error.

function validateFormOnSubmit(theForm) { 
var reason = ""; 
reason += validateUsername(theForm.username); 
reason += validatePassword(theForm.pwd); 
reason += validateEmail(; 
reason += validateEmpty(theForm.from);
 if (reason != "") { alert("Some fields need correction:\n" + reason); 
return false;
 } return true; 


To ensure that no required field is kept empty in the form we apply this method. If there is any blank space then it will return an error string or else it will return an empty string.

function validateEmpty(foo) {
    var error = "";
      if (foo.value.length == 0) { = 'Yellow'; 
        error = "The required field has not been filled in.\n"
    } else { }
    return error;   


To ensure that user has filled up the ‘username ‘ section in the form we apply this method. If there is any blank space then it will return an error string or else it will return an empty string.

function validateUsername(foo) {
    var error = "";
    if (foo.value == "") {
        error = "You didn't enter a username.\n";
    } else{};
return error;


In case of password we have to remember some other criteria like length and illegal characters in time of validating. So we should use a new regular expression to forbid under scopes. This one will allow only letters and numbers. Next, we want to permit only passwords that contain letters and at least one numeral. For that we use the seacrh() method and two more regular expressions: /(a-z)+/ and /(0-9)/.

function validatePassword(foo) {
    var error = "";
    var illegalChars = /\*$#;  
     if (foo.value == "") {
          error = "You didn't enter a password.\n";
    } else if ((foo.value.length  16)) {
        error = "The password is the wrong length. \n";
    } else if (illegalChars.test(foo.value)) {
        error = "The password contains illegal characters.\n";
    } else if (!(( && ( {
        error = "The password must contain at least one numeral.\n";
    } else { }
   return error;


Next is to check if the email address the user entered is real. This means that the input data must contain at least an @ sign and a dot (.). Also, the @ must not be the first character of the email address, and the last dot must at least be one character after the @ sign.

function trim(s)
  return s.replace(/^\s+|\s+$/, '');

function validateEmail(foo) {
    var error="";
    var foo = trim(foo.value);
    var emailFilter = /^[^@]+@[^@.]+\.[^@]*\w\w$/ ;
    var illegalChars= /[\(\)\\,\;\:\\\"\[\]]/ ;

    if (foo.value == "") {
          error = "You didn't enter an email address.\n";
    } else if (!emailFilter.test(tfoo)) {              //test email for illegal characters
        error = "Please enter a valid email address.\n";
    } else if (foo.value.match(illegalChars)) {
        error = "The email address contains illegal characters.\n";
    } else {
    return error;

If you find this article helpful, you can connect us in Google+ and Twitter.

Enter your email address:

Delivered by FeedBurner

Leave a Reply

Your email address will not be published. Required fields are marked *