简体   繁体   English

jQuery验证-将EqualTo与复选框一起使用

[英]jQuery Validation - Using EqualTo with checkboxes

I'm using the jQuery Validation Plugin for my form, and I would like to use the EqualTo rule to ensure that the input of checkbox A is the same as checkbox B. 我正在为表单使用jQuery验证插件,并且我想使用EqualTo规则来确保复选框A的输入与复选框B的输入相同。

My code: 我的代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
</head>
<body>
    <form id="form">
        <input id="A" name="A" type="checkbox"/> A<br />
        <input id="B" name="B" type="checkbox"/> B<br />
        <input type="submit" value="Submit" />
    </form>
</body>
</html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jquery-validation@1.17.0/dist/jquery.validate.js"></script>
<script>
    $("#form").validate({
        rules: {
            A: {
                equalTo: "#B"
            }
        }
    });
</script>

This doesn't work as I intended. 这不符合我的预期。 Instead, it submits if A is checked and blocks submission if A is not checked (validation did not depend on B at all!) 相反,它将提交是否选中了A,如果没有选中A,则阻止提交(验证完全不依赖于B!)

What am I doing wrong? 我究竟做错了什么?

The equalTo method is typically for comparing the values of two text elements. equalTo方法通常用于比较两个文本元素的 It's not really meant for checkboxes; 它并不是真正用于复选框; but even so, your checkboxes are missing value attributes. 但是即使如此,您的复选框仍缺少value属性。

If I add value attributes, it still does not work properly because when the checkbox is not checked, there is no value to compare and the equalTo rule is ignored. 如果添加value属性,它仍然无法正常工作,因为未选中该复选框时,没有要比较的value ,并且equalTo规则将被忽略。 In other words, both checkboxes would need to already be checked in order for the equalTo rule to compare anything, and in that case, it's pointless. 换句话说,两个复选框都需要选中,以便equalTo规则可以比较任何内容,在这种情况下,这是没有意义的。


Using the equalTo rule implies that you want validation to pass when both are checked and pass when both are un-checked. 使用equalTo规则意味着您希望同时通过验证和未选中都通过验证。

In order to do this, you would make the required rule conditional; 为此,您需要将required规则设置为条件规则。 it depends on the state of something else. 这取决于其他事物的状态。 A is only required when B is checked and vice-versa. A时才需要B检查,反之亦然。 If nothing is checked, nothing is required, so validation passes. 如果未进行任何检查,则不需要任何操作,因此验证通过。

In this example, both checkboxes must be "equal". 在此示例中,两个复选框都必须为“等于”。 Both checked or both unchecked for validation to pass. 选中或未选中均通过验证。

$("#form").validate({
    rules: {
        A: {
            required: function() {
                return $('#B').is(':checked');
            }
        },
        B: {
            required: function() {
                return $('#A').is(':checked');
            }
        }
    }, ....

DEMO: jsfiddle.net/xdxL9ewp/ 演示: jsfiddle.net/xdxL9ewp/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM