JavaScript: Date Validator

Published on Author craigzearfossLeave a comment
function isDateValid(year, month, day) {

    // Create list of days of a month [assume there is no leap year by default]
    var listofDays = [31,28,31,30,31,30,31,31,30,31,30,31];

    if (month == 1  || month > 2) {

        if (day > listofDays[month - 1]) {
            // invalid date
            return false;
        }
    }
    if (month == 2) {

        var lyear = false;

        if ( (!(year % 4) && year % 100) || !(year % 400)) {
            lyear = true;
        }

        if ((lyear == false) && (day >= 29)) {
            // invalid date (February - non-leap year)
            return false;
        }

        if ((lyear == true) && (day > 29)) {
            // invalid date (February - leap year)
            return false;
        }
    }

    return true;
}

References:

Leave a Reply

Your email address will not be published. Required fields are marked *