1. Computing
Send to a Friend via Email

Date Validation

clr gif

Validation of date fields is not a straightforward task. Not only are there different ways that a date can be entered (all numeric, alphabetic month etc.) but there are also three different formats that are used for dates in different parts of the world. The United States uses a month-day-year format, Japan uses a year-month-day format and most of the rest of the world uses day-month-year.

The complete script below not only handles both numeric and alpha months (including both upper and lower case and three letter month abbreviations) but you pass a second parameter to the validation function to tell the routine which of the three formats that the date is supposed to be in (u for MDY, j for YMD, and w for DMY). There is also a third parameter where you pass a to indicate that all dates are valid, p to indicate that future dates are invalid, and f to indicate that past dates are invalid.

The function also takes into account the first two of the three leap year rules in determining whether a 29 February is a valid date. This covers all years between 1582 and 4881 correctly. Dates outside of this range are considered to be invalid.

The first step in using this script is to select the code from the text box below (there is a highlight all button beneath it to make this easier) and copy it into a file called date.js.

You next attach the script into your web page that has forms containing date fields by adding the following code into the head section of your page.

<script type="text/javascript" src="date.js">
</script>

All that remains then is to call it using the following statement from either the onblur event of the date field itself and / or the onclick or onsubmit event of the submission button or form:

valid_date =
validateDate(date_field,format_field,range_field)

You should pass the date field that is tobe validated as date_field, the format_field should be U, J, or W to indicate the date format and the range_field shoud be A, P, or F to indicate whether all, past or future dates are valid.

The following is a working example of the date validation script:

M D Y D M Y Y M D
Past Any Future

This example extracts the selected value from the radio button groups to use as the second and third parameters by calling valDateFmt(myform.datefmt) and valDateRng(myform.daterng) respectively like this:

validateDate(myform.mydate.value,
valDateFmt(myform.datefmt),valDateRng(myform.daterng))

©2014 About.com. All rights reserved.