且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

jQuery验证:验证一个字段或一对字段中的两个字段是否都必需

更新时间:2022-12-11 21:23:52

您只需要包含

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'
        }
    });

});

class="mygroup"添加到您需要组合在一起的每个输入中...

Add class="mygroup" to each input you need to group together...

<input type="email" name="fieldEmailAddress" id="fieldEmailAddress" class="mygroup" />

最后,可以选择使用groups选项将邮件打包为一个...

And finally, optionally use the groups option to lump the messages into one...

groups: {
    theGroup: 'fieldMobileNumber fieldEmailAddress'
}

工作演示: http://jsfiddle.net/CYZZy/

如果您不喜欢将验证消息放在何处,则可以使用errorPlacement回调函数对其进行调整.

If you don't like where the validation message is placed, that's where you'd tweak it using the errorPlacement callback function.