jQuery Validate: Validate that one field, or both fields of a pair are required

匿名 (未验证) 提交于 2019-12-03 01:10:02

问题:

I have a form that I am trying to validate that has two fields:

Here's my jQuery Validation wireup:

What I'd like to do is add an additional validation rule that says: the form is not valid if both fieldEmailAddress and fieldMobileNumber are blank. In other words, I'd like to make it such that at least one of either fieldEmailAddress or fieldMobileNumber is required. It seems like most of the jQuery Validation custom methods are designed to only work for one field at a time - I need to validate both.

Any ideas?

回答1:

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...

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.



回答2:

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');     }     else if(email.val() == '') {         alert('Email, please...');     }     else if(phone.val() == '') {         alert('Phone, please...');           }     else {         alert('Yay!');     }    }); 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!