isValidDate JavaScript function

I'm working on a project right now that needs to validate a couple of fields to see if they're valid dates before submitting the form so I went out looking for JavaScript code to validate dates. Most of what I found required the author to know the format that the visitor would enter the date in, which wasn't acceptable for me, and then did a regex match to determine if it was valid.

JavaScript has a Date() object built in that does a pretty good job of parsing dates. So after looking around the web for a solution I decided to just hash out my own and came up with a remarkably simple function.

The idea is that the JavaScript function getFullYear() will return NaN if the date is invalid. So we just setup a date with the string and check if the year is numeric.

JavaScript:
  1. function isValidDate(datestring)
  2.     {
  3.     var checkdate = new Date(datestring);
  4.     if (isNaN(checkdate.getFullYear()))
  5.         {
  6.         return false;
  7.         }
  8.     else
  9.         {
  10.         return true;
  11.         }
  12.     }

To use this function just add it to your code and then write something like this.

JavaScript:
  1. if (isValidDate('Jan 1, 2007')) { return true; } else { return false; }

Of course you'll probably want to pull a variable to use instead of Jan 1, but it's pretty simple.

Question, Comments...

Do you have more questions. Please either leave a comment below or join us in our new forum.

2 Responses to “isValidDate JavaScript function”

  1. Not correct

    (new Date(“31/31/2008″)).getFullYear() == 2010

    But it is an invalid date.

  2. James –
    What browser are you using? When I wrote this originally I was using FireFox 2.something and it worked fine. But you’re right, it doesn’t appear to work in FireFox 3.

    Guess I need to do some more experimenting…

Leave a Reply