jQuery验证:验证一个字段或一对字段中的两个字段是否都必需 [英] jQuery Validate: Validate that one field, or both fields of a pair are required

查看:109
本文介绍了jQuery验证:验证一个字段或一对字段中的两个字段是否都必需的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要验证的表单,其中包含两个字段:

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

<div class="entryForm">
    <div class="formField">
        <label for="fieldEmailAddress">Email address:</label>
        <input type="email" name="fieldEmailAddress" id="fieldEmailAddress"/>
    </div>
    <div class="formField">
        <label for="fieldMobileNumber">Mobile number:</label>
        <input type="text" name="fieldMobileNumber" id="fieldMobileNumber"/>
    </div>
</div>

这是我的jQuery验证清单:

Here's my jQuery Validation wireup:

<script type="text/javascript">
    $(document).ready(function () {
        $('#form1').validate({ rules: { fieldMobileNumber: { phoneUS: true } } });
    });
</script>

我想做的是添加一条附加的验证规则,该规则说:如果fieldEmailAddress和fieldMobileNumber均为空白,则该表单无效. 我想这样做,使得fieldEmailAddress或fieldMobileNumber中的至少一个是必需的.似乎大多数jQuery Validation自定义方法都设计为一次仅适用于一个字段-我需要同时验证这两个字段.

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.

有什么想法吗?

推荐答案

您只需要包含

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.

这篇关于jQuery验证:验证一个字段或一对字段中的两个字段是否都必需的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆