How to use JavaScript to validate dates
So often I have a form on the page that includes a date field and I want to validate that date without a round trip to the server. Here is a simple JavaScript function that will do just that.
The function accepts the date value and a string indicating the format expected (i.e. ‘MDY’). Simply call this function from the form either onChange of the field or on submit of the form. I prefer the on submit approach and check all the fields at once. I find it less annoying that bugging the user on every field change.
The date validation function:
<script type='text/javascript'>
function isValidDate(dateStr, format) {
var reg = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{4}$/;
// If it doesn't conform to the right format (with either a 2 digit year or 4 digit year), fail
if (reg.test(dateStr) == false) { return false; }
var parts = dateStr.split(RegExp.$1); // Split into 3 parts based on what the divider was
// Check to see if the 3 parts end up making a valid date
var mm = parts[0];
var dd = parts[1];
var yy = parts[2];
var dt = new Date(parseFloat(yy), parseFloat(mm)-1, parseFloat(dd), 0, 0, 0, 0);
if (parseFloat(dd) != dt.getDate()) { return false; }
if (parseFloat(mm)-1 != dt.getMonth()) { return false; }
return true;
}
</script>
A sample form. This form calls a function named checkInput which calls the isValidDate function. I’ve included checkInput below the form as a reference.
<form name='formUser' action='somepage.php' method='post' enctype='multipart/form-data'>
<table>
<tbody>
<tr>
<td>Name *</td>
<td><input type="text" id="formUserName" name="formUserName" value="" size="30" maxlength="30" ></td>
</tr>
<tr>
<td>Email *</td>
<td><input type="text" id="formUserEmail" name="formUserEmail" value="" size="50" maxlength="255" ></td>
</tr>
<tr>
<td>Hire Date *</td>
<td><input type="text" id="formUserDate" name="formUserDate" value="" size="10" maxlength="10" ></td>
</tr>
<tr>
<td></td>
<td><input type='submit' id='formUserSubmit' Name='formUserSubmit' value='Save' onClick='return checkInput();'></td>
</tr>
</tbody>
</table>
</form>
<script type="text/javascript">
function checkInput()
{
if (document.formUser.formUserName.value == "") {
document.formUser.formUserName.focus();
alert('Your Name is required');
return false; }
if (document.formUser.formUserEmail.value == "") {
document.formUser.formUserEmail.focus();
alert('Your Email is required');
return false; }
if (!isValidDate(document.formUser.formUserDate.value, 'MDY') && document.formUser.formUserDate.value != '') {
document.formUser.formUserDate.focus();
alert('Date is not a valid date (ex: mm/dd/yyyy)');
return false; }
}
</script>
![]()
Click Here for a Working Example
References
HTML table
HTML form
HTML input
JavaScript alert
JavaScript document
JavaScript regular expressions
JavaScript String
JavaScript parseFloat
JavaScript Date
