JavaScript date validation

JavaScript date validation can be done in many ways like month range testing, day range testing (depending on number of days in the month) and so on. Here is shown much simpler solution. Take day, month and year from input string to create JavaScript Date object. Compare input day, month and year with day, month and year extracted from the Date() object. If they aren’t the same then the input date is not valid.

Please try how date validation works (month and day can contain leading zeros):

Enter date (m/d/yyyy):

Function is checked with JSLint (JavaScript syntax checker and validator).

function isDate(txtDate, separator) {
    var aoDate,           // needed for creating array and object
        ms,               // date in milliseconds
        month, day, year; // (integer) month, day and year
    // if separator is not defined then set '/'
    if (separator === undefined) {
        separator = '/';
    }
    // split input date to month, day and year
    aoDate = txtDate.split(separator);
    // array length should be exactly 3 (no more no less)
    if (aoDate.length !== 3) {
        return false;
    }
    // define month, day and year from array (expected format is m/d/yyyy)
    // subtraction will cast variables to integer implicitly
    month = aoDate[0] - 1; // because months in JS start from 0
    day = aoDate[1] - 0;
    year = aoDate[2] - 0;
    // test year range
    if (year < 1000 || year > 3000) {
        return false;
    }
    // convert input date to milliseconds
    ms = (new Date(year, month, day)).getTime();
    // initialize Date() object from milliseconds (reuse aoDate variable)
    aoDate = new Date();
    aoDate.setTime(ms);
    // compare input date and parts from Date() object
    // if difference exists then input date is not valid
    if (aoDate.getFullYear() !== year ||
        aoDate.getMonth() !== month ||
        aoDate.getDate() !== day) {
        return false;
    }
    // date is OK, return true
    return true;
}

isDate() function has an optional second parameter to define date separator. Default value is “/”. In case of other date format (like “d/m/yyyy”) it’s only needed to change the order of day, month and year variables after splitting the input string. The main intention was to keep this function short and simple so support for other date formats has to be done manually. And finally, see how to use date validation. checkDate() function is called on button click “Check the date” above the source code:

function checkDate(){
    // define date string to test
    var txtDate = document.getElementById('txtDate').value;
    // check date and print message
    if (isDate(txtDate)) {
        alert('OK');
    }
    else {
        alert('Invalid date format!');
    }
}

84 thoughts on “JavaScript date validation”

  1. @Boyzl – Yes, JavaScript will automatically “translate” 1/32/2012 to 2/1/2012 and that is a nice feature. But if you need to save date later to the database, I’m not sure that database will do the same. More likely that error will occure in a moment of inserting date to the table. My idea was to check date before submitting form to the server.

    And thank you for suggestion of splitting input date. isDate() is updated and it looks more elegant then before. I also added optional separator parameter.

    Regards,
    Darko, Croatia ;)

  2. I have to vehemently disagree with dbunic. Javascript’s automatic translation of “1/32/2012” to “2/1/2012” is NOT a nice feature, it is a nightmare! It makes writing a generic isValidDate(sDate) function nearly impossible. E.g.:

    These two statements are perfectly fine:

    (new Date("10/30/1961")).toString()        ->   'Mon Oct 30 00:00:00 CDT 1961'
    (new Date("October 30, 1961")).toString()  ->   'Mon Oct 30 00:00:00 CDT 1961'
    

    How the heck do I determine that “October 32” is invalid?

    (new Date("October 32, 1961")).toString()  ->   'Wed Nov 1 00:00:00 CDT 1961'
    

    “October -3” means October 3? Are you kidding me?

    (new Date("October -3, 1961")).toString()  ->   'Tue Oct 3 00:00:00 CDT 1961'
    (new Date("10/-3/1961")).toString()        ->   'Tue Oct 3 00:00:00 CDT 1961'
    

    You can’t be serious:

    (new Date("13/1/1961")).toString()         ->   'Mon Jan 1 00:00:00 CST 1962'
    

    Looks to me like some programmer decided to be “helpful” when designing the Date object. And since I can’t control the date format that someone may use, I have to program around all this “helpfulness”. It drives me insane!

  3. @Dave P – Date() object is designed (or work) on the way you described it. There’s nothing more to say. For me it is a nice feature and you have a right to disagree. Anyway, in this post my isDate() JavaScript function uses exactly this feature to validate user input. Date() object is initialized from month, day and year and returned back to the month, day and year. If any of date parts are differ from the start point then input date is not valid. The concept / idea is simple and you can use it in your JavaScript date validation code. Any other comment about JavaScript Date() object is more than welcome. Cheers!

  4. Some arguments that work improperly, both should return true, but return false:

    // dates that include time
    isDate("12/21/2012 12:54 PM");
    // dates passed in quotes
    isDate("'12/21/2012'");
    
  5. Here you go people, much much simpler, works with time also:

    function isDate(val) {
        return !isNaN(Date.parse(val));
    }
    
  6. @rob c – My intention with writing isDate() function is to show date validation idea. I saw a lot of JS code with calculation number of days in month, leap year and so on. This is much simple and I think easy to understand. On the other hand I didn’t want to complicate with input date format. If you have any JS skills you will be able to customize isDate() for your needs (like adding hours to date format).

  7. @vahid khakestani – All code from this site is provided free of charge under a liberal BSD license. So yes, you are free to use isDate() function in your plugin.

    Thanks!

  8. Hello!
    Great function, but I’m wondering, why do you not allow years before 1000 and after 3000? I’m writing a history quiz and I need to validate dates < 1000.

  9. @Hugo – For most cases this test condition will be fine but you can modify or delete it completely if not needed. Originally the idea was to allow input years approximately 1000 years to past and 1000 years to future (all other inputs are considered as wrong date).

  10. Just a quick gotcha I encountered in your script:

    aoDate.getFullYear() !== year
    

    will return true if aoDate.getFullYear() = 2012 and year = “2012” so you may want to add some parseInt’s to your Day, Month and Year variables on input.

    Otherwise great script, came in handy in a pinch.

  11. @NH – aoDate is used twice in code. First it is used as array after input date (string) is split to day, month and year. And second it’s used as date object.

    day, month and year variables are implicitly cast to integer (please see subtraction with 0 and 1), so I think parseInt is not needed in code.

    Thank you for using this script!

  12. // so simple  just one line will do
    return (new Date(your-date-string) == "Invalid Date");
    
  13. @venu – From your code I have prepared simple example:

    function dateValid(dateString) {
        // create date from input string
        var myDate = new Date(dateString),
            status = false;
        // test date
        if (myDate.toString() !== 'Invalid Date') {
            status = true;
        }
        return status;
    }
    
    // print result
    console.log(dateValid('January 16, 2013'));
    console.log(dateValid('January 36, 2013'));
    console.log(dateValid('Janaryy 36, 2013'));
    

    Output from the code is true, true and false. As you can see, only third row is printed as error while “January 36” JavaScript doesn’t consider as error. My solution covers that type of errors (valid number of days in month).

    Anyway, thank you for commenting!

  14. @Huyen Trang – No problem. As I’m a Web developer, date validation is a must on many input forms. This function was developed for Web apps and it’s in internal production for years – proven and good. Date validation can have other approaches but this one should be the simplest.

  15. Thanks for sharing! It is very helpful as I found difficulties getting the date validation working in Firefox!

Leave a Comment