How to validate Date of Birth with jQuery

In a recent project I had to implement what’s commonly referred to as a Legal Drinking Age (LDA) page. Basically what needs to happen is that the user has to enter their date of birth and thus ‘confirm’ that they are of a legal drinking age for their respective country. You can view an example of just such a page here.

This brought me to an interesting requirement – the user needs to enter their birth of date (in this case via 3 select boxes), their age then needs to be calculated from the entered date and they are either granted, or denied access based on the result.

Interestingly enough, after having a quick look around I hadn’t been able to find any similar example, so I had to come up with something myself. The following code is my solution :

var currdate = new Date();
currdate.setFullYear(currdate.getFullYear() – age);
if ((currdate – mydate) < 0){
alert("Sorry, only persons over the age of " + age + " may enter this site");
return false;
}
return true;
});
[/sourcecode]
First, we get the relevant entered date values - the “day”, “month” and “year”. I’ve also added an “age” var so that this can be easily edited if necessary – the current value is set to 18.

Next we create a Date object and call it “mydate”. We then use the object’s “setFullYear” method to set the value of “mydate” to the user’s entered birth date. You can view more information about this method here. The only thing to notice here is that we have subtract 1 from the “month” value as it’s 0 indexed.

Now that we have the user’s birth date sorted, we then create another Date object and call it “currdate”. The default value for “currdate” is the current date. We then set “currdate” to whatever the current date is minus our “age” value – i.e. Today – 18 years. Once again, we use the “setFullYear” method to set the date. However, to get the current date in a useable format, we use the “getFullYear” method and THEN subtract 18 from the resulting value. So to do this we use “currdate.getFullYear() – age”.

Once we have the date of 18 years ago and the user’s birth date, both in the same format, it’s simply a matter of making sure that the required date minus the birth date isn’t greater than 0. If so, we output an alert to inform the user then return “false” to make sure that the form doesn’t get submitted.