Validate and Format Dates
Validate and format an input date field as your visitor is actually entering it. This somewhat involved JavaScript function will automatically discard any non-numeric values that anyone attempts to type into your date field. It also automatically adds the slashes between the day, month, and year portions as well as adding leading zeros into each part of the date where the first digit that you type makes it obvious that the number must be a single digit (ie day greater than 31 or month greater than 12). The only thing it can't validate is if fewer digits are entered for the year than you require since it can't tell if you have finished entering the year until you leave the field (you would need that in an onblur test instead of the onkeyup).
So before we look at the code, let's take a look at a working date input field complete with validation and formatting as you type.
If you come from one of those countries that enter the month and day backwards then don't worry because the change to the script so it will work the way around that you want is just a matter of swapping the 12 and 31 around the other way.
So now you've seen how it works the next step is to grab the code. Let's start with the HTML. In this instance I have not made the JavaScript completely unobtrusive since passing the event itself into the event handler is a lot more complex when you do that.
<div>
<label for="mydate">Enter a date (dd/mm/ccyy)</label>
<input type="text" id="mydate" name="mydate" size="10" maxlength="10"
onkeyup="dtval(this,event)">
</div>
</form>
You can of course call your date field whatever you like. With the script coded this way the necessary values will be passed to the dtval() function regardless of what you do with the rest of the form code.
So now all we need is the code for the dtval() function itself which we can place in the same external JavaScript as the rest of our form field validation code.
Note that the capturing of the event that triggered the event handler is necessary in order that we can capture the backspace key. Since the script adds the slashes in between the parts of the date itself if we didn't have separate processing for the backspace then it wouldn't be possible to backspace past the last skash because every time we deleted it the script would put it back.

