JavaScript date validation

I was searching the web for JavaScript date validation code. All I found were lots of really bad ideas. Some were quite complicated. John Gang was on the right track. I didn’t see Chris Hogben’s article initially, but he used the right algorithm.

Still, nobody offered the complete solution. Given a date string YYYY-MM-DD, is the date valid?

The smart way to do this is to (a) parse the date string with a regular expression, (b) construct a date object and (c) compare what you got out of the date object to what you put in. To make this really convenient, we’ll use JavaScript’s proptotype functionality to extend the String class, making this available to any string:

String.prototype.isValidDate = function() {
  var IsoDateRe = new RegExp("^([0-9]{4})-([0-9]{2})-([0-9]{2})$");

  var matches = IsoDateRe.exec(this);
  if (!matches) return false;
  

  var composedDate = new Date(matches[1], (matches[2] - 1), matches[3]);

  return ((composedDate.getMonth() == (matches[2] - 1)) &&
          (composedDate.getDate() == matches[3]) &&
          (composedDate.getFullYear() == matches[1]));

}

Here’s the method in action:

var a = "2007-02-28";
alert(a + (a.isValidDate() ? " is a valid date" : " is not a valid date"));

8 Responses to “JavaScript date validation”

  1. Magga Says:

    Thank you, this is a very good script, just what I was looking for. I will reference you in my code.

  2. Chuckles Says:

    Absolute lifesaver. Just made a quick change for UK date format and all is good. Thanks

  3. Tobbe Says:

    Thanks! exactly what i needed :)

  4. kuangyee Says:

    thanks a lot.

    that’s exactly what i am looking for.

  5. manorama Says:

    Thank you very much.This was what i needed for my project.

  6. Al Says:

    This is the simpliest date validation method I found after searching the web. Thanks…

  7. blog.shrub » Blog Archive » JavaScript: how to unescape HTML entities Says:

    [...] was searching the web for JavaScript HTML entity unescaping code. I found lots of really bad ideas. Sound familiar? Some were quite [...]

  8. bemo Says:

    how to make format dd-mm-yyyy
    thanks

Leave a Reply