Javascript Date Validation Function

This section contains a lot of Scripting material for your website.

Javascript Date Validation Function

Postby Web Guru on July 27th, 2008, 5:59 am

If you are a web developer, you sometimes need to get the date input from a user through a form, you might need to validate the input date whether it is valid or not. You can validate a date using the following javascript validation function.

Code: Select all
function isValidDate(iDay, iMonth, iYear)
{
   if (iDay == 31 && (iMonth == 4 || iMonth == 6 || iMonth == 9 || iMonth == 11))
      return false;
      
   else if (iMonth == 2)
   {
      iMaxDays = ((iYear%4 == 0 && (iYear% 100 != 0 || iYear%400 == 0)) ? 29 : 28);
      
      if (iDay > iMaxDays)
         return false;
   }
      
   return true;
}


Usage
You can call the date validation function by passing the day, month and year as individual parameters and this function will returns true or false against that date.
User avatar
Web Guru
 
Posts: 68
Joined: March 24th, 2008, 7:59 am
Location: Lahore, Pakistan

Date Comparision in Javascript

Postby Web Guru on July 27th, 2008, 6:08 am

If you ever need to compare dates in javascript, you can do this easily by converting your dates into Javascript Date Objects and then you can simply compare them using simple comparisons like > , < , etc.

Lets say you are getting the date of birth of a user and wants to check whether he is 18 years old or not. This can be done easily as follows:
Code: Select all
   // these are values from the form
   var sDay   = document.frmRegister.ddDay.value;
   var sMonth = document.frmRegister.ddMonth.value;
   var sYear  = document.frmRegister.ddYear.value;

   var objNow = new Date( );
   var objDob = new Date((eval(sYear) + 18), (eval(sMonth) - 1), eval(sDay));
   
   if (objDob > objNow)
   {
      alert("You should be atleast 18 years of old to continue.");
   }

   else
   {
      alert("You can continue...");
   }
User avatar
Web Guru
 
Posts: 68
Joined: March 24th, 2008, 7:59 am
Location: Lahore, Pakistan


Return to Java Script / VB Script

Who is online

Users browsing this forum: No registered users and 0 guests

cron