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

Join the Conversation

20 Comments

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

  2. 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

  3. 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!

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

Leave a comment

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