JavaScript: isDate() Function

If you're looking at how to test whether or not a date is valid, use this JavaScript function below to test your dates. Any recommendations, improvements etc are welcome.

function isDate(year, month, day) {
   month = month - 1; // javascript month range 0 - 11
   var tempDate = new Date(year,month,day);
   if ( (year == tempDate.getFullYear()) &&
    (month == tempDate.getMonth()) &&
    (day == tempDate.getDate()) ) {
      return true;
   } else {
      return false;
   }
}

revision 1

Date.isValid = function(year, month, day) {
   month -= 1; // javascript month range 0 - 11
   var tempDate = new Date(year,month,day);
   if ( (year == tempDate.getFullYear()) &&
    (month == tempDate.getMonth()) &&
    (day == tempDate.getDate()) ) {
      return true;
   } else {
      return false;
   }
}

revision 2

This entry was posted on Wednesday, March 12th, 2008 at 7:47 pm and is filed under Programming, javascript. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

3 Responses to “JavaScript: isDate() Function”

@Dallas

I noticed you changed the function name in revision 2, and just want to note that I think isValid is a better function name as compared to isDate.

So good move and thanks to @Adrian as well.
excellent point, thanks Adrian
Why not adding it as a static method to the Date class? Something like

Date.isValid = function(year, month, day) {
...
}

This way you avoid polluting the global namespace, which is a healthy practice particularly in large applications... Cheers!

Leave a Reply