There are many examples of client side validation of date fields. Writing code to validate a date in JavaScript can turn into a large an ugly experience. That is why there are so many examples. Without a doubt, the fastest and best way to validate a field is by use of JavaScript's regular expression object. The hard part is coming up with a good regular expression to validate a date.
The regular expression in this example has been tweaked and improved by many people over many years. It will ensure any date entered in the dd-mm-yyyy format is valid. It is leap year aware.
You do not need to understand the regular expression to take advantage of the power. You can use the same technique to validate many types of fields and if you do not want to become a regular expression maven, simply check many of the fine regular expression libraries for the regex you need.
Remember: We validate form data on the client side for the convenience of the end user, to provide immediate feedback, and to prevent sending bad data to server side scripts. If the information from your form is posted to your server side script (ASP/JSP/PHP/Perl) then you must also validate the information in your server side script for security reasons. Fortunately, those languages all support regular expressions, so you will be able to use the same method to reduce your work.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="author" content="Roderick Divilbiss">
<meta name="copyright" content="© 2005-2010 Roderick Divilbiss">
<title>Date Validation</title>
<script type="text/javascript">
<!--
function validateDate(fld) {
var RegExPattern = /^((((0?[1-9]|[12]\d|3[01])[\.\-\/](0?[13578]|1[02])[\.\-\/]((1[6-9]|[2-9]\d)?\d{2}))|((0?[1-9]|[12]\d|30)[\.\-\/](0?[13456789]|1[012])[\.\-\/]((1[6-9]|[2-9]\d)?\d{2}))|((0?[1-9]|1\d|2[0-8])[\.\-\/]0?2[\.\-\/]((1[6-9]|[2-9]\d)?\d{2}))|(29[\.\-\/]0?2[\.\-\/]((1[6-9]|[2-9]\d)?(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00)|00)))|(((0[1-9]|[12]\d|3[01])(0[13578]|1[02])((1[6-9]|[2-9]\d)?\d{2}))|((0[1-9]|[12]\d|30)(0[13456789]|1[012])((1[6-9]|[2-9]\d)?\d{2}))|((0[1-9]|1\d|2[0-8])02((1[6-9]|[2-9]\d)?\d{2}))|(2902((1[6-9]|[2-9]\d)?(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00)|00))))$/;
var errorMessage = 'Please enter valid date as month, day, and four digit year.\nYou may use a slash, hyphen or period to separate the values.\nThe date must be a real date. 30/2/2000 would not be accepted.\nFormay dd/mm/yyyy.';
if ((fld.value.match(RegExPattern)) && (fld.value!='')) {
alert('Date is OK');
} else {
alert(errorMessage);
fld.focus();
}
}
//-->
</script>
</head>
<body>
<form action="dateValidate1.htm" method="post">
<p><input type="text" name="date" onblur="validateDate(this);">
<input type="button" value="Click Me">
<br>(mm/dd/yyyy)
</form>
</body>
</html>