jQuery validate across multiple fields
Follow the documentation for creating a custom method/rule. Here, I simply call it totalCheck
, but you can name it anything you wish.
$.validator.addMethod('totalCheck', function(value, element, params) {
var field_1 = $('input[name="' + params[0] + '"]').val(),
field_2 = $('input[name="' + params[1] + '"]').val();
return parseInt(value) === parseInt(field_1) + parseInt(field_2);
}, "Enter the number of persons (including yourself)");
It's implemented just like any other rule. The two parameters are the name
attributes of the two other fields you want to check against. Since this new rule says the field must contain the sum of the two other fields, the required
and digits
rules are now redundant and can be removed.
$("#form2").validate({
errorElement: "span",
rules: {
attendees: {
totalCheck: ['adults', 'children'] // <-- your custom rule
},
adults: {
required: true,
digits: true
},
children: {
required: true,
digits: true
}
},
messages: {
adults: "Enter number of adults",
children: "Enter number of childern"
}
});
Working DEMO: http://jsfiddle.net/hBXL6/
EDIT:
Added a keyup focusout
handler to re-validate attendees
whenever other fields are changed. These are the same two default event handlers used by the plugin.
$('input[name="adults"], input[name="children"]').on('keyup focusout', function() {
$('input[name="attendees"]').valid();
});
New working DEMO: http://jsfiddle.net/ua0534dv/2/
The answer by Sparky is not complete: the adults
and children
need to re-validate attendees
when changed.
Append this at the end:
$('input[name=adults],input[name=children]').on('change', function(){
$('input[name=attendees]').removeData("previousValue").valid();
});