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

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

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

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

  5. 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
    —————————————————-

  6. @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.

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

  8. 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?

  9. @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.

  10. 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;

  11. 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 ‘/'”)

  12. 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!');
        }
    }
    
  13. 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 Comment