Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / Javascript

JavaScript Date Validation

5.00/5 (2 votes)
17 Jan 2011CPOL 15.9K  
Your statement of, I wanted to validate text inputed by a user as they were typing to tell them if it was a valid date. seems to be a bit misleading. I was under the impression that your code would start off returning true until I entered a non-number character, invalid separator, or invalid...
Your statement of, "I wanted to validate text inputed by a user as they were typing to tell them if it was a valid date." seems to be a bit misleading. I was under the impression that your code would start off returning true until I entered a non-number character, invalid separator, or invalid range for the month/day/year position I was in. However, your method doesn't appear to do this. I've written a test program and wired up a textbox to the onkeyup event to call your method and it only returns true when a complete and accurate date has been entered.

I think there are many ways to do this so I'm surprised you didn't find an existing example that met your needs. Personally, I use a regular expression. The below regular expression even handles leap years.

function isDate(value)
{
   var dateRegEx = new RegExp(/^(?:(?:(?:0?[13578]|1[02])(\/|-)31)|(?:(?:0?[1,3-9]|1[0-2])(\/|-)(?:29|30)))(\/|-)(?:[1-9]\d\d\d|\d[1-9]\d\d|\d\d[1-9]\d|\d\d\d[1-9])$|^(?:(?:0?[1-9]|1[0-2])(\/|-)(?:0?[1-9]|1\d|2[0-8]))(\/|-)(?:[1-9]\d\d\d|\d[1-9]\d\d|\d\d[1-9]\d|\d\d\d[1-9])$|^(0?2(\/|-)29)(\/|-)(?:(?:0[48]00|[13579][26]00|[2468][048]00)|(?:\d\d)?(?:0[48]|[2468][048]|[13579][26]))$/);

   if (dateRegEx.test(value))
   {
      return true;
   }
   return false;
}


I did not write this regular expression myself so I do not take credit for it. I don't recall where I found it, but it was years ago and I haven't had any problems with it in any of my applications.

I've also used Prerak Patel alternate method when I have separate form fields for each date part.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)