While working on a client project, we needed a way to ensure a user was at least 13 years old before submitting a form. We were already using the jQuery Validation plugin for the form validation method but it didn’t have a method for checking for a minimum age.
The jQuery Validation plugin makes client-side form validation easy. It comes with a bunch of useful validation methods like required, email, url, date, etc. jQuery Validation does not have a standard method to require a minimum age for a field but it is easy to create a custom validation method.
<input type="date" name="dob" placeholder="mm/dd/yyyy"/>
We need to extend the plugin to create a custom validation method for checking a minimum age using the data of birth:
$.validator.addMethod("minAge", function(value, element, min) { var today = new Date(); var birthDate = new Date(value); var age = today.getFullYear() - birthDate.getFullYear(); if (age > min+1) { return true; } var m = today.getMonth() - birthDate.getMonth(); if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) { age--; } return age >= min; }, "You are not old enough!");
We can use this custom method to validate a minimum age:
$("form").validate({ rules: { dob: { required: true, minAge: 13 } }, messages: { dob: { required: "Please enter you date of birth.", minAge: "You must be at least 13 years old!" } } });