Published:

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;
}

 


Subscribe or Follow Me For Updates

Subscribe to my YouTube channel or follow me on Twitter, Facebook or GitHub to be notified when I post new content.

Other than coding...

I'm currently attempting to travel around Australia by motorcycle with my wife Tina on a pair of Royal Enfield Himalayans. You can follow our adventures on YouTube, Instagram and Facebook.


Need Some jQuery Help?

Search fiverr to find help quickly from experienced jQuery developers.



Supported by