Web Development

Date Validation with JavaScript

By Hervé Deschamps.

I have finally won a battle (not the war) with JavaScript date validations. To save you time if you hit the same problem, I though of sharing the code with you.

The requirement was extra simple: when the user enters the effective date, the browser must issue an error message if the date is greater than sysdate. This is a JavaScript job.

In PL/SQL, this is simple:
if eff_date < sysdate then
end if;

In JavaScript.... it's another story. Here's the code:

function EFFECTIVE_DATE_OnChange(ctl) {

// enforce date later than sysdate
   var cal = new Array();
   cal.JAN = "January";
   cal.FEB = "February";
   cal.MAR = "March";
   cal.APR = "April";
   cal.MAY = "May";
   cal.JUN = "June";
   cal.JUL = "July";
   cal.AUG = "August";
   cal.SEP = "September";
   cal.OCT = "October";
   cal.NOV = "November";
   cal.DEC = "December";

   var sysDate = new Date();
   var effDateChar = ctl.value; // P_EFFECTIVE_DATE

   // translate date entered by user into JS format
   var bufArray = effDateChar.split("-");
   var effDateMonth = cal[bufArray[1].toUpperCase()];
   var effDateDay = bufArray[0];
   var effDateYear = bufArray[2];
   var effDateDate = new Date(effDateMonth+" "+ effDateDay +
                       ", "+effDateYear+" 23:59:59");

   // compare the 2 dates
   if (effDateDate < sysDate)
     {alert("The effective date must be today's date or a later date.");
      return false;
   return true;

The rule is that you have to be extra careful with dates handling in JavaScript. Pretty soon, you will all need a JavaScript reference book even more than a PL/SQL book. The one I use is "JavaScript Bible", 3rd edition, Danny Goodman.

Please send me comments or suggestions:  herve@iherve.com
 Take a look at my HomePage