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. @Jim – I’m not sure why you have to change from “!==” to “!=” in the last if statement to make this function work. isDate() is checked with JSlint and tested in FireFox 3.5, Google Chrome 9 and Internet Explorer 8. Did you make any other modification in code and in which browser this problem occurs?

  2. @dbunic I did make one modification to the code which I have found out caused the problem although I’m not sure why. I wanted to check for the format yyyy/mm/dd so I made the following change:

    // extract month, day and year from the txtDate (expected format is yyyy/mm/dd)  
    // subtraction will cast variables to integer implicitly  
    month = txtDate.substring(5, 7) - 1; // because months in JS start from 0  
    day = txtDate.substring(8, 10);  
    year = txtDate.substring(0, 4);
    
  3. @Jim – You should add subtraction with zero to cast “day” and “year” variables to integer.

    day = txtDate.substring(8, 10) - 0;  
    year = txtDate.substring(0, 4) - 0;
    

    Or you can use parseInt:

    day = parseInt(txtDate.substring(8, 10), 10);
    year = parseInt(txtDate.substring(0, 4), 10);
    

    If using the triple equals (or !== operator), the values must be equal in type as well. In your case you compared string with integer and that was false.

  4. i want javascript validation for From date n To date fields…….. can u help me as soon as possilble plzzzzzz

  5. @Tejasvi ware – If you have two input boxes for date data type, isDate() function can be used for both fields. After user clicks on save button (or any other button to finish the input process) form validation should go straight after. Inside validate() function you will have to validate both dates – that’s nothing new – but you will have to check if first date precedes the second date. So, with all of the mentioned conditions, validate() function may look like this:

    // compare two dates and return the number of days between dat1 and dat2
    // date format is dd.mm.yyyy
    // if dat2 precedes dat1, then the result will be negative
    // this function is needed in validate()
    function cmpDate(dat1, dat2) {
    	// define local variables
    	var day, mSec1, mSec2;
    	// number of milliseconds in one day
    	day = 1000 * 60 * 60 * 24;
    	// define number of milliseconds for both dates
    	mSec1 = (new Date(dat1.substring(6, 10), dat1.substring(3, 5) - 1, dat1.substring(0, 2))).getTime();
    	mSec2 = (new Date(dat2.substring(6, 10), dat2.substring(3, 5) - 1, dat2.substring(0, 2))).getTime();
    	// return number of days between dat1 and dat2
    	return Math.ceil((mSec2 - mSec1) / day);
    }
    
    // input form validation (in this example, form contains only two dates)
    // this function is called after the user has finished entering data
    function validate() {
    	// define reference to the input form and set dat1 and dat2 variables
    	var frm = document.forms[0],
    		dat1 = frm.dat1.value,
    		dat2 = frm.dat2.value;
    	// test first date
    	if (!isDate(dat1)) {
    		alert('Invalid date1 ...');
    		return;
    	}
    	// test second date
    	if (!isDate(dat2)) {
    		alert('Invalid date2 ...');
    		return;
    	}
    	// date1 should precede date2
    	if (cmpDate(dat1, dat2) < 0) {
    		alert('Date1 should precede date2!');
    		return;
    	}
    	// if everything is OK, then you can submit form
    	// frm.submit();
    }
    

    Hope this code snippet will give you some hints of how to check "From" and "To" input dates ...

  6. Great site & great info – thx!

    I’ve been looking all week for a good date validation routine that can work without using forms or any buttons. Would yours work on a different event? Everyone and their mother have it onSubmit with forms – Geez!!!

    Thx,
    KJ

  7. /*
     * This function validates date for yyyy-mm-dd format
     * year range is 1900-2100
     * ( if required modified the range by changing YL & YU )
     * Note - dtStr parameter contains date i.e 2011-04-27 in string format
     * Author - Vikramjit Saha
     * eMail - vikramjitsaha@msn.com
     */
    function isFilterDateFormat(dtStr) {
        var msg1 = "Enter date in yyyy-mm-dd format";
        var YL = 1900; // Lower limit for year
        var YU = 2100; // Upper limit for year	
        if (dtStr.length == 10) {
            var date_array = dtStr.split("-");
    
            if (date_array.length < 3) {
                alert(msg1);
                return false;
            }
            else {
                var strYear = date_array[0];
                var strMonth = date_array[1];
                var strDay = date_array[2];
    
                var year = parseInt(strYear);
                var month = parseInt(strMonth);
                var day = parseInt(strDay);
    
                for (var i = 0; i < date_array.length; i++) {
                	// starting year validation
                    if (i == 0) {
                        if (strYear.length != 4) {
                            alert('Enter year in yyyy format');
                            return false;
                        }
                        else {
                            if (!isFilterNumeric(strYear)) {
                                alert('Enter numeric value for year');
                                return false;
                            } else {
                                if (yearYU) {
                                    alert('Enter year between 1900 & 2100');
                                    return false;
                                }
                            }
                        }
                    } //End of year validation
                    // starting month validation
                    if (i == 1) {
                        if (strMonth.length != 2) {
                            alert('Enter month in mm format');
                            return false;
                        }
                        else {
                            if (!isFilterNumeric(strMonth)) {
                                alert('Enter numeric value for month');
                                return false;
                            }
                            else {
                                if (month12) {
                                    alert('Enter month between 01 & 12');
                                    return false;
                                }
                            }
                        }
                    } // End of month validation
                    // starting day validation
                    if (i == 2) {
                        if (strDay.length != 2) {
                            alert('Enter day in dd format');
                            return false;
                        }
                        else {
                            if (!isFilterNumeric(strDay)) {
                                alert('Enter numeric value for date');
                                return false;
                            }
                            else {
                                if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {
                                    if (day > 31) {
                                        alert('For month ' + month + ' enter day between 01 & 31');
                                        return false;
                                    }
                                }
                                else if (month == 4 || month == 6 || month == 9 || month == 11) {
                                    if (day > 30) {
                                        alert('For month ' + month + ' enter day between 01 & 30');
                                        return false;
                                    }
                                }
                                else if (month == 2) {
                                	// Leap year check
                                    if (year % 4 == 0) {
                                        var flg = false;
                                        if (year % 100 != 0) flg = true;
                                        else if (datea % 400 == 0) flg = true;
                                        if (flg) {
                                            if (day > 29) {
                                                alert('For Leap year ' + year + ' & month ' + month + ' enter day between 01 & 29');
                                                return false;
                                            }
                                        }
                                    }
                                    else {
                                        if (day > 28) {
                                            alert('For month ' + month + ' enter day between 01 & 28');
                                            return false;
                                        }
                                    }
                                }
                            }
                        }
                    } //End of day Validation
                }
            }
        }
        else {
            alert(msg1);
            return false;
        }
        return true;
    }
    
  8. @KJ – isDate() is a simple JavaScript function and can be called from any event handler you need. In this demo, date validation is called on button click. Please see HTML code of “Check the date” button.

    @Vikramjit – Your solution contains much refined error messages then my isDate() function. It is helpful but price for that is amount of code and elegancy. Anyway, thank you for posting your version of date validation. Cheers!

  9. Wow that’s a lot of code I just use:

    function isDate(txtDate) {
        filter=/^([0-1][0-2]|[0]\d{1})\/([0]\d{1}|[0-1][0-9]|[0-2][0-9]|[0-3][0-1])\/(\d{2}|\d{4})$/;
        if (filter.test(txtDate)) {
            return true;
        }
        else {
            alert("Please enter a valid date (mm/dd/yy) or (mm/dd/yyyy)");
        }
        return false;
    }
    
  10. @Scott – Yes, your code is short but it doesn’t verify if month have 30 or 31 day or if February has 28 or 29 days. That’s the reason why converting txtDate to milliseconds and returning it back. Returned date (from milliseconds) is compared to txtDate and if difference exists, then input date is wrong …

  11. Hi dbunic
    could you help in validation of a date where a user should not be able to select a date prior to 2 weeks of the todays date. Means a user can select a date for 2 weeks prior to todays date but it should not allow user to select date before those 2 weeks.
    i have a datetime picker in my form where a user can click to select the date and a calender opens a date is selected.

  12. @vijay – Here is code snippet to test if input date is in valid range:

    var day = 1000 * 60 * 60 * 24,         // number of milliseconds in one day
        dat1 = Date.parse('Jun 25, 2011'), // user input
        dat2 = Date.now() - 14 * day,      // 14 days before today
        diff;                        
    
    // calculate difference between two dates
    diff = Math.ceil((dat1 - dat2) / day);
    
    // if the difference is negative then input date is older than two weeks ago
    if (diff < 0) {
        alert('Input date is older than two weeks ago!');
    }
    

    User input should be verified before testing date range.

  13. Only discuss that validation of date format. dont check if the date is correct

  14. I don’t have experience with javascript. I’d like to know how can you perform a check on two or more text fields in one web page. Can you provide me with a working code? thanks.

  15. @annse – Here is modification of checkDate() function to test two date fields on page. chechDate() can be called before form submit or any other event (like button click):

    function checkDate(){
        // prepare dates for testing
        var txtDate1 = document.getElementById('txtDate1').value,
            txtDate2 = document.getElementById('txtDate2').value;
        // check date1
        if (isDate(txtDate1)) {
            alert('OK');
        }
        else {
            alert('Invalid date1 format!');
        }
        // check date2
        if (isDate(txtDate2)) {
            alert('OK');
        }
        else {
            alert('Invalid date2 format!');
        }
    }
    
  16. thanks Darko for taking the time to reply to my post. more success to you. cheers!

  17. Hi , In popular sites i observed one thing , instead of entering date , they give on button. when we click on it one calender is opening. can u provide the code for that task.

  18. @sanjay – JavaScript date picker is a bit complex code and it can’t fit in a few lines. Anyway, my goal was to show simple date validation in a case when user has option to manually input date. I’m sure there are plenty of good date pickers, so creation of a new one is not currently on my task list. ;)

Leave a Comment