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.
-
function isValidDate(datestring)
-
{
-
var checkdate = new Date(datestring);
-
if (isNaN(checkdate.getFullYear()))
-
{
-
return false;
-
}
-
else
-
{
-
return true;
-
}
-
}
To use this function just add it to your code and then write something like this.
-
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.
Not correct
(new Date(”31/31/2008″)).getFullYear() == 2010
But it is an invalid date.
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…