Click here to Skip to main content
Click here to Skip to main content
Alternative Tip/Trick

Tagged as

JavaScript Date Validation

, 17 Jan 2011 CPOL
Rate this:
Please Sign up or sign in to vote.
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)

Share

About the Author

KevinAG

United States United States
No Biography provided

Comments and Discussions

 
GeneralUS format dates only, though. PinmemberGladToBeGrey28-Sep-11 4:30 
GeneralHi there, Yes I can see why that would be an obvious assum... PinmemberEdMan19618-Jan-11 0:35 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.141220.1 | Last Updated 18 Jan 2011
Article Copyright 2011 by KevinAG
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid