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.
- Subscribe on YouTube at https://www.youtube.com/JasonWatmore
- Follow me on Twitter at https://twitter.com/jason_watmore
- Follow me on Facebook at https://www.facebook.com/JasonWatmoreBlog
- Follow me on GitHub at https://github.com/cornflourblue
- Feed formats available: RSS, Atom, JSON
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.
- Subscribe on YouTube at https://www.youtube.com/TinaAndJason
- Follow us on Instagram at https://www.instagram.com/tinaandjason
- Follow us on Facebook at https://www.facebook.com/TinaAndJasonVlog
- Visit our website at https://tinaandjason.com.au
Need Some jQuery Help?
Search fiverr to find help quickly from experienced jQuery developers.