Click here to Skip to main content
15,881,380 members
Articles / Programming Languages / Javascript
Alternative
Tip/Trick

JavaScript Date Validation

Rate me:
Please Sign up or sign in to vote.
5.00/5 (2 votes)
17 Jan 2011CPOL 15.2K   2
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)


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralUS format dates only, though. Pin
gladtobegrey28-Sep-11 3:30
gladtobegrey28-Sep-11 3:30 
GeneralHi there, Yes I can see why that would be an obvious assum... Pin
Ed Nutting17-Jan-11 23:35
Ed Nutting17-Jan-11 23:35 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.