Date validation in javascript

The below JavaScript function will validate date for the following formats.
1. mm/dd/yyyy
2. mm/dd/yy
3. mm-dd-yyyy
4. mm-dd-yy

JavaScript function

//Checks date for mm/dd/yyyy, mm/dd/yy, mm-dd-yyyy and mm-dd-yy format. function checkDate(inputdate) { if (inputdate == '') return false; var rxDatePattern = /^(0[1-9]|1[012])[-](0[1-9]|[12][0-9]|3[01])[-]((?:19|20)\d\d)$/ var dtArray = inputdate.match(rxDatePattern); if (dtArray == null) { rxDatePattern = /^(0[1-9]|1[012])[\/](0[1-9]|[12][0-9]|3[01])[\/]((?:19|20)\d\d)$/ dtArray = inputdate.match(rxDatePattern); if (dtArray == null) return false; } dtMonth = dtArray[1]; dtDay = dtArray[2]; dtYear = dtArray[3]; if (dtMonth < 1 || dtMonth > 12) return false; else if (dtDay < 1 || dtDay > 31) return false; else if ((dtMonth == 4 || dtMonth == 6 || dtMonth == 9 || dtMonth == 11) && dtDay == 31) return false; else if (dtMonth == 2) { var isleap = (dtYear % 4 == 0 && (dtYear % 100 != 0 || dtYear % 400 == 0)); if (dtDay > 29 || (dtDay == 29 && !isleap)) return false; } return true; }

Example
date validation in javascript

Example source code

<html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> <script language="javascript"> //Checks date for mm/dd/yyyy, mm/dd/yy, mm-dd-yyyy and mm-dd-yy format. function checkDate(inputdate) { if (inputdate == '') return false; var rxDatePattern = /^(0[1-9]|1[012])[-](0[1-9]|[12][0-9]|3[01])[-]((?:19|20)\d\d)$/ var dtArray = inputdate.match(rxDatePattern); if (dtArray == null) { rxDatePattern = /^(0[1-9]|1[012])[\/](0[1-9]|[12][0-9]|3[01])[\/]((?:19|20)\d\d)$/ dtArray = inputdate.match(rxDatePattern); if (dtArray == null) return false; } dtMonth = dtArray[1]; dtDay = dtArray[2]; dtYear = dtArray[3]; if (dtMonth < 1 || dtMonth > 12) return false; else if (dtDay < 1 || dtDay > 31) return false; else if ((dtMonth == 4 || dtMonth == 6 || dtMonth == 9 || dtMonth == 11) && dtDay == 31) return false; else if (dtMonth == 2) { var isleap = (dtYear % 4 == 0 && (dtYear % 100 != 0 || dtYear % 400 == 0)); if (dtDay > 29 || (dtDay == 29 && !isleap)) return false; } return true; } function validatedate() { if (checkDate(document.getElementById("txtDate").value)) { document.getElementById("divmsg").innerHTML = "Valid Date."; document.getElementById("divmsg").style.color = "green"; } else { document.getElementById("divmsg").innerHTML = "Invalid Date."; document.getElementById("divmsg").style.color = "red"; } } </script> </head> <body> Date : <input id="txtDate" type="text" value="11/19/2015"> <input type="button" value="Validate" onclick="validatedate();" /> <br /> <br /> <div id="divmsg"> </div> </body> </html>