jQuery form validator example

A form validator with jQuery is an useful coding exercise. Let's start with a basic form like this:

<form action="#" method="post" enctype="multipart/form-data">

<ul>
 <li id="for-name"><label for="name">First Name:</label>
 <input type="text" name="name" id="name" />
 </li>
 <li id="for-last"><label for="last">Last Name:</label>
 <input type="text" name="last" id="last" />
 </li>
 <li id="for-email"><label for="email">Email:</label>
 <input type="text" name="email" id="email" /></li>
 <li id="for-subject"><label for="subject">Subject:</label>
 <input type="text" name="subject" id="subject" />
 </li>
 <li id="for-url"><label for="url">URL:</label>
 <input type="text" name="url" id="url" />
 </li>
 <li id="for-message"><label for="message">Message:</label>
 <textarea id="message" name="message" cols="25" rows="15"></textarea>
 </li>
</ul>

<p><input type="submit" value="Send" name="send" id="send" /></p>
</form>

What we need is:

  1. a base form validation class that we'll call jVal
  2. a script that implements this base class.

Let's start with the base class:

function jVal() {
    this.message = function (element, klass, message, position) {
 position = position || "after";
        element = $(element);
 if(arguments[3] == null) {
     arguments[3] = "after";
 }
 if(arguments[3] == "after") {
     $('<div></div>').addClass(klass).html(message).insertAfter(element);
 } else if(arguments[3] == "before") {
     $('<div></div>').addClass(klass).html(message).insertBefore(element);
 }
 
 
    }
    
    this.reg = function (re, element) {
        re = new RegExp(re);
 element = $(element).val();
 return re.test(element);
    }
    
    this.regi = function (re, element) {
 re = new RegExp(re, "i");
 element = $(element).val();
 return re.test(element);
    }
    
    this.is_empty = function(element) {
        element = $(element).val();
 var re = /.+/;
 if(element.length == 0 || element == '' ||
    !re.test(element)) {
    return true;
 } else {
   return false;
 }
    }
    
    this.specialchars = function(element) {
        element = $(element).val();
 if(element.indexOf(">") != -1 || element.indexOf(">") != -1 ||
    element.indexOf("\\") != -1) {
      return true;
 } else {
      return false;
 }
    }
    
    this.parse_url = function (element) {
        element = $(element).val();
 var re = /^https?:\/\/([a-z0-9]+\.)+[a-z0-9]{2,7}.*$/;
 return re.test(element);
    }

This class has only a few basic methods as its members, because it's only for a demonstrative purpose. The actual validation process is dispatched to the script that will implement it, which is as follows:

var validateForm = function () {
  var F = new jVal();

  var valid;
  if(!F.reg("^[a-zA-Z]{2,20}$", '#name')) {
     F.message('#name', 'error', 'This field must contain only letters and cannot be less than 2 characters.');
     valid = false;
  }
  if(!F.reg("^[a-zA-Z]{2,20}$", '#last')) {
     F.message('#last', 'error', 'This field must contain only letters and cannot be less than 2 characters.', 'before');
     valid = false;
  }
  
  if(!F.regi("^[a-z-0-9_+.-]+\\@([a-z0-9-]+\\.)+[a-z0-9]{2,7}$", '#email')) {
      F.message('#email', 'error', 'This is not a valid email address.');
      valid = false;
  }
  
  if(F.reg("<|>|&|\\$|%|\\/|\\*|@|#|\\|", '#subject')|| F.is_empty('#subject')) {
      F.message('#subject', 'error', 'This field cannot contain special characters or be empty.', 'before');
      valid = false;
  }

  if(!F.parse_url('#url')) {
      F.message('#url', 'error', 'This is not a valid URL.');
      valid = false;
  }
      
   
  if(F.specialchars('#message') || F.is_empty('#message')) {
      F.message('#message', 'error', 'This field cannot contain special characters or be empty.', 'before');
      valid = false;
  
  }
  
  
  return valid;
  
  
  
}

$(document).ready(function() {
    $('form[method=post]').submit(validateForm);
});

As you can see, the above function checks only if all the field values are in the correct format. If not, it show an error message on each field and prevent the form from being submitted. You can see the final result here.

Leave a Reply

Note: Only a member of this blog may post a comment.