How to Verify User Age with jQuery Code

If you've ever visited a site that's selling a product that has certain age restrictions (for example, a site selling or representing an alcohol brand might prompt you to verify that you're over 21 before you're allowed access to the site), you might have come into contact with an age verification form. It turns out, that this type of form is a fairly easy one to validate, because all you need to do is prove whether it's true or false that someone is older than the desired age cut off for access to your site.

The jQuery snippet you can use to validate this type of form is as follows:

$("#age-verify").submit(function() {
    var day = $("#day").val();
    var month = $("#month").val();
    var year = $("#year").val();
    var age = 21;
    var mydate = new Date();
    mydate.setFullYear(year, month - 1, day);
    var currdate = new Date();
    currdate.setFullYear(currdate.getFullYear() - age);
    if ((currdate - mydate) & lt; 0) {
        alert("Sorry, only persons over the age of " + age + " may enter this site");
        return false;
    return true;

The code above assumes that the only relevant information you're collecting from your age verification form (here it has the id #age-verify - - be sure to change it to match the id of your own form) is the day, month, and year of your users birth. The age variable sets the minimum age of users allowed access to your site. For the purposes of this example, we've made the minimum age 21.

Using some simple arithmetic and an if else statement, the snippet above determines whether a person is over 21 by checking if the current date subtracted by the age variable is greater than zero. If it is, then they are allowed access to the site, and if it isn't, they're presented with a "Sorry, you're not old enough" message. Of course, there's nothing about this form that wouldn't stop an under age user from simply lying about the year of their birth, but the same is true with implementations of this type of form across the board, including with big, international brands.