I would like to have some validation on a date field. The date format is
dd/mm which is used for our financial year end. I suppose I need also
consider leap years. Please can you shed some light on how I will be
able to achieve this?
The easiest way is to validate the format of the date, then use the
built-in Date object to verify the actual numbers are valid. This is
performed by creating a Date object with the given values, then check that
you get those numbers back (the Date object corrects dates automatically,
so the month and day won't match with out-of-range numbers).
The only question I must ask is how is the year determined? Is it always
the current year or does it differ? I've assumed the current year in the
code below. I've also heavily commented the code so you can see what's
going on.
<!-- Change the id values as you wish. Also remember the name
-- attribute if you intend to submit the value to a server.
-->
<label for="myDate">Date (dd/mm):
<input id="myDate" size="5" onchange="checkDate(this);">
</label>
function checkDate(obj) {
/* Returns an array that contains three elements if the date is
* valid, or null if invalid.
* 0 - The value that matches the regular expression
* 1 - The day
* 2 - The month
*/
var valid = /^([0123]\d)\/([01]\d)$/.exec(obj.value);
/* If the return value is an array, it will be type-converted to
* boolean true. The value, null, is type-converted to false.
*/
if(valid) {
/* Create a new Date object, initialised to the current date.
* This automatically provides the current year. Also, convert
* the user input to numbers using unary plus (+).
* Note that month values start at zero, not one (hence the -1).
*/
var date = new Date(),
day = +valid[1],
month = +valid[2] - 1;
/* Change the date object to reflect the user input. */
date.setMonth(month, day);
/* Compare the values returned by the Date object with those
* provided by the user. If they match, the input is valid.
*/
valid = (date.getDate() == day) && (date.getMonth() == month);
}
/* This part is optional. If the value is not valid, alert the
* user.
*/
if(!valid) {
alert('Please enter a valid date.');
obj.focus();
}
/* This is also optional. If you use this function in a longer
* validation sequence, such as one that might be used when the
* form submits, this return signals whether the value was in
* fact, valid.
*/
return valid;
}
Partially tested.
This example use the change event for the INPUT control. The value should
also be examined when the form is submitted using the FORM's submit event
and, of course, on the server.
Hope that helps,
Mike