Skip to content

Instantly share code, notes, and snippets.

@danwill
Last active October 27, 2023 10:55
Show Gist options
  • Save danwill/4678174 to your computer and use it in GitHub Desktop.
Save danwill/4678174 to your computer and use it in GitHub Desktop.
Javascript: Age validation with jquery.validate.js #snippet
$.validator.addMethod("checkage", function(value, element, params) {
var subDate, userDate, today, diff;
subDate = getSubmittedDate(); // some function that returns the user's birthdate as a Date
userDate = new Date((subDate.getFullYear() + params), subDate.getMonth(), subDate.getDate());
today = new Date();
diff = today.getTime() - userDate.getTime();
return diff > -1;
}, "You must be over " + params.toString() + " to enter");
$('#my-form').validate({
groups: {
dob: "age_dob_month age_dob_day age_dob_year age_dob"
},
rules: {
age_dob_month: "required",
age_dob_day: "required",
age_dob_year: "required",
age_dob: {
required: true,
checkage: 21
}
}
}
<!-- SNIP -->
<div id="dob-input">
<label for="dob_month">Birthdate</label>
<select id="dob_month" name="dob_month">
<option value="">Month</option>
</select>
<select id="dob_day" name="dob_day">
<option value="">Day</option>
</select>
<select id="dob_year" name="dob_year">
<option value="">Year</option>
</select>
<div class="hidden-field"><input id="dob" name="dob" type="text"/></div>
</div>
.hidden-field input {
visibility: hidden;
height: 0;
}
.hidden-field {
width: auto;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment