Tuesday, December 20, 2011

Validate Date using jQuery


I have already posted about "Validate Date format using jQuery" in which explains how to validate the format of date only, not the actual date. I also received one comment from my reader that it is not sufficient to validate only format. So I thought why not writing a post which validates the date as well. So how do we validate the date using jQuery?


Well, I have created a function which takes date value as input and returns true/false based on date validation logic. Below is the jQuery function which validates the date. The function does following things. Please take a look at the function first.
  • Checks the value is empty or not.
  • It then validates the date against the regular expression defined in the function.
  • Then the input date is split into 3 different array for day, month and year.
  • Then the each array is checked against validation for example, month is not greater then 12.
  • Based on the validation, the function returns true or false.
function isDate(txtDate)
{
  var currVal = txtDate;
  if(currVal == '')
    return false;
  
  //Declare Regex  
  var rxDatePattern = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/; 
  var dtArray = currVal.match(rxDatePattern); // is format OK?

  if (dtArray == null)
     return false;
 
  //Checks for mm/dd/yyyy format.
  dtMonth = dtArray[1];
  dtDay= dtArray[3];
  dtYear = dtArray[5];

  if (dtMonth < 1 || dtMonth > 12)
      return false;
  else if (dtDay < 1 || dtDay> 31)
      return false;
  else if ((dtMonth==4 || dtMonth==6 || dtMonth==9 || dtMonth==11) && dtDay ==31)
      return false;
  else if (dtMonth == 2)
  {
     var isleap = (dtYear % 4 == 0 && (dtYear % 100 != 0 || dtYear % 400 == 0));
     if (dtDay> 29 || (dtDay ==29 && !isleap))
          return false;
  }
  return true;
}
Note: The above method checks for mm/dd/yyyy format. If you want to validate against the dd/mm/yyyy format then you make the slight change in this function. Change below code in function to,
//Checks for mm/dd/yyyy format.
    dtMonth = dtArray[1];
    dtDay= dtArray[3];
    dtYear = dtArray[5];        
this code.
//Checks for dd/mm/yyyy format.
    dtDay = dtArray[1];
    dtMonth= dtArray[3];
    dtYear = dtArray[5];   
Now, all you need to do is to call this function on button click to validate the date. Below jQuery code shows exactly the same thing.
$(function() {
    $('#btnSubmit').bind('click', function(){
        var txtVal =  $('#txtDate').val();
        if(isDate(txtVal))
            alert('Valid Date');
        else
            alert('Invalid Date');
    });
});
That's it....
See live Demo and Code.
Feel free to contact me for any help related to jQuery, I will gladly help you.