breaking into the unknown…

jQuery form validation

Leave a comment

It is always good to validate a form before submitting to server, So that, server do not need to do unwanted processing or throw a error, for example, email should be never blank, certain field should contain only number, terms and condition must be accepted etc. Let, us construct a sample form, with some input fields, which we will validate using jQuery.

  <label>Your Lucky Number</label>
  <input type="text" value="" id="number" />

  <label>Your Email</label>
  <input type="text" value="" id="email" />

  <label>Your Date of Birth</label>
  <input type="text" value="" id="dob" />

  <label>Your Password</label>
  <input type="text" value="" id="password" />

  <label>Are you happy</label>
  <select value="" id="happy">
    <option selected="selected" value="">Please Select</option>
    <option value="YES">YES</option>
    <option value="NO">NO</option>

  <input type="checkbox" value="confirmation" name="accept_tc" id="accept_tc" />

  <input type="submit" value="Submit" id="form-submit">

We can write different validation as below.


  // validateEmail function is defined to validate email format
  var validateEmail =  function(sEmail){
        var filter = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
            return true;
            return false;

    // below method will validate that year should be in four digit. I have assumed that
       dob field is populated by jQuery calender which feed date in format: day-month-year.
       this function will return validation status and error message, you can add manymore
       validation with error message, you want. see later how it is used to validate dob
       before the form submit
   // complete validation for date is available in this post
   var validated_dob = function(dob){
        var dob_split = dob.split("-")
        var validated = "NO"
        var msg = "Date of Birth should be in format: day-month-year"
        if(dob_split.length == 3){
            if (dob_split[2].length != 4){
                msg = "Date of Birth Year should be in 4 digits"
                return [validated, msg]
                validated = "YES"
                msg = "Date of Birth is valid"
                return [validated, msg]
            return [validated, msg]


// collect input values in different variables which we will use 
//in different validation test on them
var lucky_number = $("#number").val()
var email = $("#email").val()
var dob = $("#dob").val()
var mood = $("#happy").val()
var password = $("#password").val()
var tnc = $("#accept_tc").val()

// validating the input to be defined or avoiding undefined
// sometime it happen that some input may be not loaded by dom due to some reason, may be
// your code have put some condition on display of password so it may not be displayed on some scenerio
// so to avoid error, you can check its type before performing some action on it
// validating undefined
if(typeof password != "undefined" && password.length < 8){
 alert("password must be of more then 8 charecter")
  return false

// validating presence of fields
if(lucky_number == "" || email == "" || mood == ""){
  alert("All fields are required to Submit Credit Request.") # you can do any other stuff then alert
  return false # it will prevent the form from submit

// validating input password length
if (password.length != 10){
  alert("Your password must contain 10 charecters")
  return false
// validating input to be a number
if (!(/^[0-9]+$/).test(lucky_number)){
  alert("Lucky number can have only numeric value")
  return false

// validate two input fields say email and password do not have the same value
if (email == password)){
  alert("email and password can't be same")
  return false

// validate email format
if (!(validateEmail(email))){
   alert('Your Email Address is Invalid');
   return false

// validate date of birth
  var check_dob = validated_dob(dob) # check_dob will collect array returned by validated_dob
     if (check_dob[0] == "NO"){
        return false

// terms and condition check-box must be selected validation
if (!$("#accept_tc").is(':checked'))
   alert("Please read and accept the terms,before submitting the form.")
   return false


Note above that, while validating things we use a number of operators. Some of the most commonly used operators are as below

#Logical AND and OR operators

var me = 1;
var you = 0;
var us = 2;

me || you; # returns 1, which is true
you || me; # returns 1, which is true
me && you; # returns 0, which is false
me && us; # returns 2, which is true
us && me; #returns 1, which is true

#Comparison operators

var me = 1;
var you = 0;
var us = "1";
var we = 2;

me == you; # false
me != you; # true
me == us; # true; do not match the type
me === us; # false ; it match the type also
me !== us; # true
me === parseInt( us ); # true
me > we; # false
we > us; # true
me <= us; # true

Author: arunyadav4u

over 7 years experience in web development with Ruby on Rails.Involved in all stage of development lifecycle : requirement gathering, planing, coding, deployment & Knowledge transfer. I can adept to any situation, mixup very easily with people & can be a great friend.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s