I need to validate date of birth by using jquery validator with three separate textbox for day month and year.
How to do this please help.
HTML code
You should create a custom validation method for this, along with using the groups
option that validate provides:
/* Custom validation method to validate a date based on several fields: */
$.validator.addMethod("datemultiple", function(value, element, params) {
var daySelector = params[0],
monthSelector = params[1],
yearSelector = params[2],
day = parseInt($(daySelector).val(), 10),
month = parseInt($(monthSelector).val(), 10),
year = parseInt($(yearSelector).val(), 10),
dateEntered = new Date(year, month - 1, day);
return this.optional(element) || !isNaN(dateEntered.valueOf());
}, "Please enter a valid date");
$(document).ready(function() {
$("#myform").validate({
groups: {
/* Only display one validation message for day, month, and year: */
dateOfBirth: "dob-day dob-month dob-year"
},
rules: {
'dob-day': {
required: true,
datemultiple: ["#dob-day", "#dob-month", "#dob-year"]
},
'dob-month': {
required: true
}
},
/* Place error messages after the "year" field */
errorPlacement: function ($error, $element) {
if ($element.data("fieldgroup") === "dob") {
$error.insertAfter("#dob-year");
}
}
});
});
Example: http://jsfiddle.net/xHC86/