Validating a Date

Perhaps the most complicated part of being able to validate a date that someone filling out a form might have entered is that different parts of the world use different formats for how they type dates. If someone enters a date as 12/10/11 you have no way to tell whether that date is in October or December 2011 or in October 2012 as any of three possibilities are valid depending on where in the world the person entering the date lives. The simplest solution to this particular issue is to supply three separate fields for the day, month, and year to be entered separately so that you can label which is which rather than having to try to guess which way around a date has been entered into a single field.

With separate fields for the day, month and year the validation of our date becomes much simpler. All we need to do is to check that all three are numeric and then try to load them into a Date object. If they do not represent a valid date then the individual parts within the Date object we create will not be the same as the parts we started with.

The following JavaScript not only includes all these validations to return true or false depending on whether the date is valid or not. The month value is assumed to be the expected 01 through 12 and not the value one less that JavaScript uses internally with its month processing. The function returns false if the date supplied is invalid and returns a date object containing the date if it is valid.

validateDate = function(y,m,d) {
var dt;
if (d !== +d || m !== +m || y !== +y) return false;
dt = new Date(y, --m, d);
if (d !== dt.getDate() || m !== dt.getMonth() || y !== dt.getFullYear()) return false;
return dt;


This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow