jQuery根据复选框验证不同的字段 [英] jQuery validate different field depending on a checkbox

查看:59
本文介绍了jQuery根据复选框验证不同的字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 jQuery验证插件来验证我在一个应用程序中拥有的表单.

I'm trying to use jQuery validation plugin to validate a form I have on one of my applications.

(简化)形式如下:

<form id="my_form" action="#" method="post" novalidate="novalidate">
    <input id="my_hidden_input" type="text" style="display:none;">
    <input id="my_select_checkbox" class="checkbox" type="checkbox" value="1">
    <select id="my_select_1" class="select valid" type="select">
    <select id="my_select_2" class="select valid" type="select">
</form>

我要做的是验证以下内容:如果选中了该复选框,那么我将检查我的第一次选择中是否选中了一个值;如果未选中此复选框,则我将检查选中的值.第二个列表.

What I'm trying to do is to validate the following : if the checkbox is checked, I check that a value is selected in my first select, and if the checkbox isn't checked, I check the selected value of my second list.

我尝试过类似的事情:

$('#my_form').validate({ // initialize the plugin
    rules: {
        my_hidden_input:{
            "checkboxSelect": true,
        },
    },
    submitHandler: function (form) { // for demo
        console.log($("#monitors_start").value);
        return false;
    }
});


jQuery.validator.addMethod(
    "checkboxSelect",
    function() {
        if ($("#my_select_checkbox").attr('checked'))
            return $("#my_select_1").val();
        else
        return $("#my_select_2").val();
    }, "test addMethod"
);

但是看来我没有得到正确的解决……如果有人可以帮助的话,将不胜感激!

But it seems i'm not getting it properly... If anybody could help it'd be greatly appreciated !

谢谢!

推荐答案

您可以使用Depends选项,例如

You can use the depends option like

var validator = $('#form').validate({
    rules: {
        my_select_1: {
            required: {
                depends: function () {
                    return $('#my_select_checkbox').is(':checked')
                }
            }
        },
        my_select_2: {
            required: {
                depends: function () {
                    return !$('#my_select_checkbox').is(':checked')
                }
            }
        }
    },
    messages: {}
});

演示:小提琴

这篇关于jQuery根据复选框验证不同的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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