Javascript date validation

Working on a WordPress calendar plugin, I needed some kind of Javascript date validation. As JS doesn’t have a native date validation function, I googled a bit and came across various validation methods, from REGEX to some overcomplicated stuff, so I decided to write my own function.

I have noticed that the Javascript Date Object has a very interesting behavior.

Let’s take a look at the following example where we pass the year and the month as parameters:

new Date(2012, 12)

Note that the months are numbered from 0 (January) to 11 (December), so in the above example 12 wouldn’t make sense. There’s no 13th month!

But outputting that Date Object will result in something rather interesting:

Tue Jan 01 2013 00:00:00 GMT+0200 (GTB Standard Time)

It added another month to the time and calculated the date accordingly.

What do you think the following piece of code will output?

new Date(2012, 13)

If your answer was something like this:

Fri Feb 01 2013 00:00:00 GMT+0200 (GTB Standard Time)

Then you were right!

What this means is that the Date Object calculates the time relatively if we are specifying an “invalid” (from our point of view) date.

With this in mind, all we have to do is compare the information we pass to the Date Object with the information it returns. If the information is the same before and after, then the date is valid.

Here’s what I came up with:

function is_valid_date(year, month, day, hours, minutes, seconds, milliseconds)
{

  if (year == null)
    return false;

  // Set some default values
  // Note that the months are numbered from 0 to 11
  month = month != null ? month - 1 : 0;
  // The days are numbered from 1 to 31
  day = day != null ? day : 1;
  hours = hours != null ? hours : 0;
  minutes = minutes != null ? minutes : 0;
  seconds = seconds != null ? seconds : 0;
  milliseconds = milliseconds != null ? milliseconds : 0;

  // Create the Date Object
  date = new Date(year, month, day, hours, minutes, seconds, milliseconds);

  // If any of these do not match, then the date is invalid
  if (year != date.getFullYear() || month != date.getMonth() || day != date.getDate() ||
      hours != date.getHours() || minutes != date.getMinutes() || seconds != date.getSeconds() ||
      milliseconds != date.getMilliseconds())
    return false;

  return true;
}

It’s not as short as a REGEX date validation, but unlike that, this method can correctly tell if the date really exists or not.

For the human comfort, the month parameter of this function ranges from 1 to 12.

Also note that all the parameters except the year parameter are optional.

To use this function is pretty straightforward, but here are a few examples, anyway:

alert(is_valid_date(2012, 12)); // true

alert(is_valid_date(2012, 2, 29)); // true

alert(is_valid_date(2013, 2, 29)); // false

Enjoy :)

Leave a Reply