PixelfearWeb Development by Jason Varga

Validating a Minimum Age with jQuery.validate

JQuery, JavaScript, Tips

I was working on a project and needed a way to make sure a user was at least 18 years old before submitting a form.

I’m using jQuery Validate for client-side form validation, it’s a great plugin. In addition to a bunch of pre-defined validation rules - like required fields and email addresses - you can create your own. So that’s what we are going to do.

The form had the date of birth using 3 dropdowns - day, month and year. It’s in this format because my CMS was storing the data this way.

<select name="dob_day" id="dob_day" class="required">
    <option value="">Day</option>
    <option value="1">1</option>
</select>
<select name="dob_month" id="dob_month" class="required">
    <option value="">Month</option>
    <option value="1">January</option>
</select>
<select name="dob_year" id="dob_year" class="required">
    <option value="">Year</option>
    <option value="2012">2012</option>
</select>

Your code will obviously need more than one option per dropdown. It’s like this for readability.

You’ll need to extend the plugin by creating your own validation method.

$.validator.addMethod("check_date_of_birth", function(value, element) {

    var day = $("#dob_day").val();
    var month = $("#dob_month").val();
    var year = $("#dob_year").val();
    var age =  18;

    var mydate = new Date();
    mydate.setFullYear(year, month-1, day);

    var currdate = new Date();
    currdate.setFullYear(currdate.getFullYear() - age);

    return currdate > mydate;

}, "You must be at least 18 years of age.");

Lastly, pop the new rule into your plugin call.

$("form").validate({
    rules: {
        dob_year: { check_date_of_birth: true }
    }
});

In the rules, dob_year is the name of the year dropdown. It doesn’t matter which of the three dropdowns you use, but I used year, so the error will show up after it in the DOM - makes the most sense.

Comments

blog comments powered by Disqus