Jquery Validate: Validate That One Field, Or Both Fields Of A Pair Are Required
I have a form that I am trying to validate that has two fields:
Solution 1:
You can bypass the Validate plugin and do a check like the following:
$("#form1").submit(function() {
var email = $('#fieldEmailAddress');
var phone = $('#fieldMobileNumber');
if(email.val() == '' && phone.val() == '') {
alert('Fill out both fields');
}
elseif(email.val() == '') {
alert('Email, please...');
}
elseif(phone.val() == '') {
alert('Phone, please...');
}
else {
alert('Yay!');
}
});
Solution 2:
You simply need to include the additional-methods.js
file and use the require_from_group
method.
require_from_group: [x, '.class']
// x = number of items required from a group of items.// .class = class assigned to every form element included in the group.
jQuery:
$(document).ready(function () {
$('#form1').validate({
rules: {
fieldMobileNumber: {
phoneUS: true,
require_from_group: [1, '.mygroup']
},
fieldEmailAddress: {
require_from_group: [1, '.mygroup']
}
},
groups: {
theGroup: 'fieldMobileNumber fieldEmailAddress'
}
});
});
Add class="mygroup"
to each input you need to group together...
<inputtype="email" name="fieldEmailAddress"id="fieldEmailAddress"class="mygroup" />
And finally, optionally use the groups
option to lump the messages into one...
groups: {
theGroup: 'fieldMobileNumber fieldEmailAddress'
}
Working DEMO: http://jsfiddle.net/CYZZy/
If you don't like where the validation message is placed, that's where you'd tweak it using the errorPlacement
callback function.
Post a Comment for "Jquery Validate: Validate That One Field, Or Both Fields Of A Pair Are Required"