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. Hi
    If we pass date string to date object and check if there is any exception and catch that exception, do you think it will work.

  2. @Gajendra – That might work, but I’m not sure if Date object will throw an exeption for incorrect input. Here is example:

    var mydate = Date('qwerty');
    console.log(mydate);
    

    Instead of exception JavaScript will print current date:

    Sat Dec 03 2011 11:41:57 GMT+0100 (CET)
    

    Was it your idea or did you have something else in mind? Any other opinion is more then welcome.

  3. I will appreciate if you can provide the full code and script for this example here.

  4. @gondai – The full code for testing date is already shown. In onclick event listener of Check the date button checkDate() function is called. You can see how alert is displayed depending on return value from isDate() function. The nice part of Web is that nothing can be hidden. You can always peek under the hood and see the source of any component of HTML page (except Flash). Yes, scripts can be minimized and hard to read, but there is option to un-minimize and beautify the code.

  5. Thank you so much for this code. With slight modifications I have been able to validate YYYY-MM-DD

  6. Hi. Thanks for the great code and discussion. What I am searching for is a way to access a stated MinDate and MaxDate from our forms (different for each form) and use them in the JavaScript to complete the validation. (I’m using ASPX)
    Here is a snippet of my code:

    I can get into the validation code and do the validating on the client. I just can’t find a way to access and use the min and max dates within that same JavaScript.

    Thanks in advance!

  7. @Will – you need to compare dates. Here is small JS code for a such function:

    // compare dates and return number of days between
    function cmpDate(dat1, dat2) {
        var day = 1000 * 60 * 60 * 24, // milliseconds in one day
            mSec1, mSec2;              // milliseconds for dat1 and dat2
        // valudate dates
        if (!isDate(dat1) || !isDate(dat2)) {
            alert("cmpDate: Input parameters are not dates!");
            return 0;
        }
        // prepare milliseconds for dat1 and dat2
        mSec1 = (new Date(dat1.substring(6, 10), dat1.substring(0, 2) - 1, dat1.substring(3, 5))).getTime();
        mSec2 = (new Date(dat2.substring(6, 10), dat2.substring(0, 2) - 1, dat2.substring(3, 5))).getTime();
        // return number of days (positive or negative)
        return Math.ceil((mSec2 - mSec1) / day);
    }
    

    … and example of how to use it:

    var dat1 = '01/23/2011',
        dat2 = '01/24/2011';
        
    if (cmpDate(dat1, dat2) > 0) {
        alert('Dat1 is prior dat2!');
    }
    else if (cmpDate(dat1, dat2) < 0) {
        alert('Dat1 is after dat2!');
    }
    else {
        alert('Dat1 and dat2 are the same!');
    }
    

    Hope this will help.

  8. @dbunic – Thanks for the reply. Unfortunately my code snippet did not get included, so I was not clear in my question.
    I’ll try to include the code. Here is part of my form:

    Later in the validation function

    function DateValidatorEvaluateIsValid(val) {
        var control = document.getElementById(val.controltovalidate);
    

    I can check for a valid date format but do not know how to get the MinDate and MaxDate from the form to test in the function.

  9. @dbunic Say, how do I include blocks of code here? I suspect I need to insert some special code or something. Thanks!

  10. @Will – I changed instructions below comment. Now you can see HTML elements that can be used in comment (any other HTML tag will be stripped). Anyway, before posting JS code or HTML you can (or should) replace every occurence of:

    "<" with "&lt;"
    

    … (just make search and replace before posting). After your comment is posted, I will place it inside box to be easier for reading. Thanks!

  11. @dbunic
    Thanks – I’ll try again.

    What I am searching for is a way to access a stated MinDate and MaxDate from our forms (different for each form) and use them in the JavaScript to complete the validation. Here is a snippet of my code in ASPX:

    <MyStuff:DateTextBox ID="adate" runat="Server" Pattern="MM/dd/yyyy" />
    <MyStuff:DateValidator ID="dateValidator" runat="Server" ControlToValidate="adate" ErrorMessage="Please enter a date in the following format {0} that falls between {1} and {2}." MinDate="1/1/1940" MaxDate="12/31/2011" />
    

    Later in my JavaScript validation function (here I just show the header)

    function DateValidatorEvaluateIsValid(val) {
        var control = document.getElementById(val.controltovalidate);
    

    I can get into the validation code and do the validating on the client(i.e. confirm it is a date, etc). I just can’t find a way to access and use the min and max dates within that same JavaScript. If I hard code a MaxDate and Mindate I can use them to validate. So, the function will work as desired when I can access the Min and Max Dates from the form. Any insight/help would be greatly appreciated!

  12. @Will – Maybe you can prepare min/max date with aspx logic as hidden parameters within each form like this:

    <form method="get" action="some_script.aspx">
    <input type="hidden" name="minDate" value="01/01/1940"/>
    <input type="hidden" name="maxDate" value="12/31/2011"/>
    ...
    

    After date range is on the client side it easy to access and use for validation. Here is how to access dates from first form (second form will have index 1):

    // set form reference and minDate/maxDate
    var frm = document.forms[0],
        minDate = frm.minDate.value,
        maxDate = frm.maxDate.value;
    // display minDate and maxDate
    alert(minDate + ' ' + maxDate);
    

    Hope this hint will give you a direction of how to use date ranges for validation. If you’ll have any other question, please don’t hesitate to comment.

  13. @dbunic That is a creative solution. I was expecting some way to access the MinDate and MaxDate on the MyStuff:DateValidator line from within the JavaScript function. But this works too.
    Thanks for your help!

  14. You can allow users to either include or exclude the leading zeros on the month and day by using the split() function instead of using substring …

    arrDate = txtDate.split('/');
    

    Then just use arrDate[n] instead of txtDate.substring()

  15. @barbecue – You are right. Good point! I will update code to use split() method instead of substring(). Thanks!

  16. Hi,
    nice code, but why not leaving it to JavaScript itself, it’s pretty powerfull working with dates? This would do almost the same:

    var datestring = .....
    var d=new Date.parse(datestring);
    if (d.toString() == 'NaN' || d.toString() == 'Invalid Date' || datestring == ''){
    	alert('Not a date');
    }else{
    	alert('A valid date: ' + d);
    }
    

    Except your code alerts an error with dates that do not exist and JavaScript adjusts it by itself. e.g. JavaScript adjusts string

    30.02.2012 to 01.03.2012

    which can be useful too (or not – then your code does it better, I admitt: it depends on usage ;-)). Not to forget: the above code works with all various formats: dd.mm.yyyy, d.m.yyyy, yyyy-mm-dd,…

    PS: when your code is better it would be advisable to use:

    var datearray = datestring.split('/'));
    new Date(datearray[0], datearray[1],datearray[2]);
    

    to be independent of leading zeros in input string.

    Regards,
    Boyzl, Ljubljana, SI

Leave a Comment