JavaScript date validation

More...

JavaScript date validation can be done in many ways, like month range testing, then day range testing (depend on month) and so on. I suggest simpler solution. Take day, month and year from string to create a Date object. Compare day, month and year with day, month and year extracted from the Date() object. If they aren't the same, than the input date is not valid.

Please try how date validation works:

Enter date (mm/dd/yyyy):

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

function isDate(txtDate) {
    var objDate,  // date object initialized from the txtDate string
        mSeconds, // txtDate in milliseconds
        day,      // day
        month,    // month
        year;     // year
    // date length should be 10 characters (no more no less)
    if (txtDate.length !== 10) {
        return false;
    }
    // third and sixth character should be '/'
    if (txtDate.substring(2, 3) !== '/' || txtDate.substring(5, 6) !== '/') {
        return false;
    }
    // extract month, day and year from the txtDate (expected format is mm/dd/yyyy)
    // subtraction will cast variables to integer implicitly (needed
    // for !== comparing)
    month = txtDate.substring(0, 2) - 1; // because months in JS start from 0
    day = txtDate.substring(3, 5) - 0;
    year = txtDate.substring(6, 10) - 0;
    // test year range
    if (year < 1000 || year > 3000) {
        return false;
    }
    // convert txtDate to milliseconds
    mSeconds = (new Date(year, month, day)).getTime();
    // initialize Date() object from calculated milliseconds
    objDate = new Date();
    objDate.setTime(mSeconds);
    // compare input date and parts from Date() object
    // if difference exists then date isn't valid
    if (objDate.getFullYear() !== year ||
        objDate.getMonth() !== month ||
        objDate.getDate() !== day) {
        return false;
    }
    // otherwise return true
    return true;
}

And finally, see how to use date validation function. checkDate() is called on button click.

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!');
    }
}

This entry was posted on January 23, 2009 and is filed under JavaScript

Related posts

53 Responses to JavaScript date validation

  1. red_screen says:

    Nice Script!

  2. newbie says:

    Thanks, one of the most elegant scripts I've seen that checks the date ...

  3. Amal says:

    Nice work!! Cleverly done.

  4. everest says:

    good script

  5. b0ris says:

    A very good one, thanks, you spared me some work hours :)

  6. rivka says:

    thank's a lot!a great great solution

  7. Richard says:

    This is a great script - simple solution and nice comments. Thanks for sharing!

    I made a simple edit that I wanted to share in case it helps anyone. By using the split() function to grab the date pieces (rather than specific indices) you can support single digit months and days.

    Here is the updated code (replacing lines 7 - 20 above):

    // date length should be 8-10 characters - no more, no less
    if ((txtDate.length 10)) return false;

    // extract day, month and year from the txtDate string
    var dateArray = txtDate.split("/");
    if (dateArray.length !== 3) return false; // should only have 2 '/' chars

    // subtraction will cast variables to integer implicitly
    var month = dateArray[0] - 1; // months in JS start with 0
    var day = dateArray[1] - 0;
    var year = dateArray[2] - 0;

    // test year range
    ....

  8. Richard says:

    Sorry - left a few mistakes in the last post.

    1) New form allows 8-10 characters, so length test should read:
    if ((txtDate.length 10)) return false;

    2) Converting a sting to a number using subtraction will remove any trailing decimals (e.g. "12.") or zero value decimals (e.g. "12.0"). Depending on how you're sending the date information to the server, any decimals in the string may cause issues. Therefore, you can check for any "." characters and fail if they exist.
    if (txtDate.indexOf(".") !== -1) return false;

  9. Priyanka says:

    Its realy a nice script i m searching 4 the date validation 4m past 2 days.
    Now i got it want i want.
    Thanka a lot.

  10. prasuna says:

    how can we validate a date according to the system specific culture.imean to say the scipt shud check the dates in UK and US formats either with'-' or '.' or '/'. iam able to get the system format used and i wanna validate the date on that format please advice

  11. milacay says:

    First, I would like to thank you the author who posted this script. It is really useful.

    Secondly, I like to thanks Richard's method for allow "single digit month", even though there was some typo in your code, which will not going to work.

    Here is the modification and hope it helps someone wants to allow single digit month and day also.

    Replace this below
    ----------------------------------------------------
    // date length should be 10 characters - no more, no less
    if (txtDate.length != 10) return false;

    // extract day, month and year from the txtDate string
    // expected format is mm/dd/yyyy
    // subtraction will cast variables to integer implicitly
    var day = txtDate.substring(3,5) - 0;
    var month = txtDate.substring(0,2) - 1; // because months in JS start with 0
    var year = txtDate.substring(6,10) - 0;

    // third and sixth character should be /
    if (txtDate.substring(2,3) != '/') return false;
    if (txtDate.substring(5,6) != '/') return false;
    ----------------------------------------------------
    Replace with this:
    ----------------------------------------------------
    // date length should between 8 to 10 characters
    alert("length: " + txtDate.length)
    if (txtDate.length 10) return false;

    var dateArray = txtDate.split("/");
    alert("Array: " + dateArray.length);
    if (dateArray.length != 3) return false; // shoud only have 2 "/" chars

    // subtraction will cast variabls to integer implicitly
    var month = dateArray[0] - 1; //Months in JS start with 0
    var day = dateArray[1] - 0; // Day
    var year = dateArray[2] - 0; // Year
    ----------------------------------------------------

  12. dbunic says:

    @Richard - Thanks!

    @milacay - Thank you for improving date validation code with single digit month and day. Date validation script will show the trick how to initialize Date() object from string, return string back and compare values. If values doesn't match, then something is wrong with input date. I tried to make script short so it has room for improvement like yours. Thank you once again.

  13. santosh says:

    10/31/2010
    Is this a valid date? Try inputting the same...! :-)

  14. dbunic says:

    @santosh - Yes, this is valid date. After clicking on "Check this date" for 10/31/2010 script responses with "OK". There should not be any problem. Can you give me a little bit more details about your case.

    Thanks!

  15. santosh says:

    I'm sorry, for giving invalid entry...! I wanted to do with dd/mm/yy not mm/dd/yyyy...! Can you help me out with this?

  16. dbunic says:

    @santosh - This demo works with mm/dd/yyyy format, but you are free to modify/customize date validation for your needs. Instead of substring definitions:

    month = txtDate.substring(0,2)  - 1; // because months in JS start with 0
    day   = txtDate.substring(3,5)  - 0;
    year  = txtDate.substring(6,10) - 0;
    

    You can modify lines for dd/mm/yy format:

    day   = txtDate.substring(0,2)  - 0;
    month = txtDate.substring(3,5)  - 1; // because months in JS start with 0
    year  = txtDate.substring(6,8)*1 + 2000;
    

    Multiply with 1 will cast to numeric value. If you leave only "+ 2000" then you will get string concatenation. And don't forget:

    if (txtDate.length !== 8 ) {return false;}
    

    at the script beginning.

  17. thank you for help in code for validation of date in javascript

    if (!isDate(fobj.mnth.value+'-'+fobj.dt.value+'-'+fobj.yr.value)) {
      alert('Invalid date');
      return false;
    }
    return true;

  18. dbunic says:

    As I can see from your example, you have separate input fields for date input. After concatenation you called isDate() function for validation. My demo expects mm/dd/yyyy date format and '/' as separator. Instead of '-' for concatenation please use '/' or just wipe out or change separator checker in isDate() validator (lines after comment "third and sixth character should be '/'")

  19. Sizzler says:

    Thanks for the script. It was clean and efficient. For my project I needed something like accepting DDMMYYYY and MMDDYYYY and separators like "." "-" "/" "\". Concatenate and display 0 if single digit is entered for day/month. I modified the script, find the script below. Greatly appreciated if anyone can make this better

    function isDate(txtDate,gDateFormat) {
        var objDate,  // date object initialized from the txtDate string
            mSeconds,
            day,
            month,
            year;
    
        // check for separators
        if(txtDate.indexOf(".")!=-1)
            dateSeparator = ".";
        else if(txtDate.indexOf("/")!=-1)
            dateSeparator = "/";
        else if(txtDate.indexOf("\\")!=-1)
            dateSeparator = "\\";
        else if(txtDate.indexOf("-")!=-1)
            dateSeparator = "-";
        else
            return false;
    
        var dateArray = txtDate.split(dateSeparator);
        if(dateArray.length  3) return false;
    
        // initialize Date() object from calculated milliseconds
        objDate = new Date();
    
        if(gDateFormat == "MMDDYYYY")
        {
            month = dateArray[0] - 1; //Months in JS start with 0
            day = dateArray[1] - 0; // Day
        }
        else if(gDateFormat == "DDMMYYYY")
        {
            month = dateArray[1] - 1; //Months in JS start with 0
            day = dateArray[0] - 0; // Day
        }
        else
        {
            return false;
        }
    
        //if year is not entered, then consider the current year
        if(dateArray.length == 2)
            year = objDate.getFullYear();
        else
            year = dateArray[2] - 0; // Year
    
        // test year range
        if (year  3000) {
            return false;
        }
    
        // convert txtDate to milliseconds
        mSeconds = (new Date(year, month, day)).getTime();
    
        objDate.setTime(mSeconds);
    
        // compare input date and parts from Date() object
    
        // if difference exists then date isn't valid
        if (objDate.getFullYear() !== year ||
            objDate.getMonth() !== month ||
            objDate.getDate() !== day) {
            return false;
        }
        // otherwise return true
    
        month = month + 1;
    
        // concatenate zero if single digit eneterd for day\month
    
        if(String(day).length == 1)
            day = "0" + day;
        if(String(month).length == 1)
            month = "0" + month;
    
        if(gDateFormat == "DDMMYYYY")
            return day + "-" + month + "-" + year;
        else if(gDateFormat == "MMDDYYYY")
            return month + "-" + day + "-" + year;
        else
            return false;
    }
    
    function checkDate(){
        // define date string to test
        var txtDate = document.getElementById('txtDate').value;
        // check date and print message
        isValidDate = isDate(txtDate,"DDMMYYYY");
        if (isValidDate) {
            document.getElementById('txtDate').value = isValidDate;
        }
        else {
        alert('Invalid date format!');
        }
    }
    
  20. Jim says:

    Not sure if anyone mentioned this but in order for it to work I had to change the triple equals/not equals operators in the last if statement to:

    if (objDate.getFullYear() != year ||
        objDate.getMonth() != month ||
        objDate.getDate() != day)
    

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=""> <strike> <strong>