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"));

17 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. Pingback: blog.shrub » Blog Archive » JavaScript: how to unescape HTML entities

  8. bemo says:

    how to make format dd-mm-yyyy
    thanks

  9. zack says:

    hello..

    actually i’m looking 4 this solution too..about yyyy-mm-dd format…even i didn’t find the exact solution but then, i mix up two javacript example i found in the internet….just wanna share my knowledge..
    then become like dis..:p

    //———-start

    function isValidDate()
    {

    var datePat = /^(19|20)\d\d[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])$/;//yyyy-mm-dd 1900-2099

    dateStr = document.form.dob.value;//just change dis input value name to use

    var M = dateStr.match(datePat); // is the format ok?
    var s = dateStr.split(/\D/);
    var d = new Date(s[0]*1,s[1]-1,s[2]*1);
    var L = d.lastDay()[s[1]-1];

    if(!(M && s[2]<=L))
    {
    alert(“Date format is wrong”);
    }

    }

    Date.prototype.lastDay=function()
    {
    var A=[];
    for(var i=1; i<=12; i++) {
    A[A.length]= new Date(this.getFullYear(), i,0).getDate();
    }

    return A;
    }

    //—————–end

    -the datePat regular expression is to validate year exactly from year 1900-2099 n for the month+day will not really accurate if below problem occur
    -the Date.prototype.lastDay=function() is to validate the day+month, as example if 1999-02-30 were entered…it will know dat is wrong…
    -this code validate all…cover all event! :p

    -bemo,

    bout the dd-mm-yyyy, i’ll try to create one if i have free time..:D

    //human knowledge belong to the world!!!!!!!!!
    //zack de maniac

  10. Nuwan Chamara says:

    Thanks for this article. This article is really helpful.

  11. WorldClassProgrammer says:

    While this may be a reasonable and fairly effective solution,
    This explanation is FAR above the heads of all those expect skilled professionals who have years of expertise under their belts.
    Rather than benefit only those with advanced knowledge, why not post an easier to understand implementation example?
    For the lesser skilled of course.
    After all, this was posted with the intent to assist others was it not?
    Cheers!

  12. Aakanksha Tewari says:

    Thank you very much. This article is very simple and helpful.

  13. Parthasarathy says:

    Thanks a lot…
    Its simple & easy to get going

  14. Pingback: Javascript: how to validate dates in format MM-DD-YYYY? | BlogoSfera

  15. Pingback: Javascript: how to validate dates in format MM-DD-YYYY? | Ask & Answers

  16. Pingback: Javascript: how to validate dates in format MM-DD-YYYY? | Technology & Programming

  17. p says:

    This gives me an error “Uncaught SyntaxError: Unexpected number ” at the line starting “var composedDate = “

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>