Last active
October 27, 2023 10:55
-
-
Save danwill/4678174 to your computer and use it in GitHub Desktop.
Javascript: Age validation with jquery.validate.js #snippet
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$.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 | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- 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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
.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