how to validate a date in javascript

Not many people are aware that the date object in javascript has intrinsic knowledge of dates. It’s a misconception that date validation has to be a lenghty process.

Let’s consider the regular Y,M,D format, where a date is set using

var date=new Date(y,m,d);

Now we can take advantage of the fact that javascript will automatically rewrite a date to it’s nearest valid neighbour. Take e.g. Dec 32nd, 2006. Of course this date does not exist, and javascript knows this! That’s why it is automatically converted to Jan 1st, 2007. With this knowledge we can conclude that any valid date will not be altered, and any invalid date will be altered by javascript. Thus to test for a valid date all we need to test is if the date parameter values y,m and d have changed or not.

Here’s how:

function isDate(y,m,d)
{
var date = new Date(y,m-1,d);
var convertedDate =
""+date.getFullYear() + (date.getMonth()+1) + date.getDate();
var givenDate = "" + y + m + d;
return ( givenDate == convertedDate);
}

Now to test it, here’s an example, checking Jan 40th, 2007.

window.alert (isDate(2007,1,40));

This will show ‘false’.

If that doesn’t convince you, try

window.alert (isDate(2007,2,29));

How about that?

4 comments so far

  1. Steve on

    Thanks for this post. I was looking all over the web getting really disgusted that there wasn’t a straight forward way to solve this problem without hand writing a slew of complicated code to do a task that should just be built into the language.

    I like your solution because it is straight forward and therefore less prone to error. Thank You!

  2. michiel on

    Glad to help!

  3. Eric Hahn on

    HI Michiel,

    would it be possible to alter what you have above to test that a user choose a particular ‘day’- date and date format are unimportant in that they are forced to choose from a pop up calendar- but i can’t seem to make them choose a sunday start date via the calender widgit, so i thought i’d just validate that they choose a sunday…

    any ideas?

    Thanks!!
    eric

  4. js on

    Thanks for taking the time – very helpful.


Leave a reply