Published: November 18 2011

Validate date dropdown lists with JavaScript / jQuery

A simple javascript function for validating a date that's input using 3 dropdown lists:

function validateDate()
{
    var ddlDay = $("#ddlDay");
    var ddlMonth = $("#ddlMonth");
    var ddlYear = $("#ddlYear");

    // check date was selected
    if (ddlDay[0].selectedIndex == 0 ||
        ddlMonth[0].selectedIndex == 0 ||
        ddlYear[0].selectedIndex == 0)
    {
        alert("date is required!");
        return false;
    }

    // check date is valid
    var date = new Date();
    date.setFullYear(ddlYear.val(), ddlMonth.val() - 1, ddlDay.val());
    var inputDate = ddlYear.val() + "-" + (ddlMonth.val() - 1) + "-" + ddlDay.val();
    var parsedDate = date.getFullYear() + "-" + date.getMonth() + "-" + date.getDate();
    // the parsed date will only match the input date if the input date is valid
    if (inputDate != parsedDate)
    {
        alert("date is invalid!");
        return false;
    }

    // date is valid
    return true;
}

 


Need Some jQuery Help?

Search fiverr for freelance jQuery developers.


Follow me for updates

On Twitter or RSS.


When I'm not coding...

Me and Tina are on a motorcycle adventure around Australia.
Come along for the ride!


Comments


Supported by