繁体   English   中英

使用自定义验证程序对嵌套输入进行条件jquery验证

[英]Conditional jquery validation on nested inputs with custom validator

我有以下HTML:

<div class='headerWithYesNo'>
    <p>Text....</p>
    <div class='choices'>
        <input type="radio" name="choices" value="yes" />
        <input type="radio" name="choices" value="no" />
    </div>
    <div class='headerWithYesNoChild hidden'>
        <input type="checkbox" />
        <input type="checkbox" />
    </div>
</div>

我有一个jQuery验证程序,要求用户选择是或否。 当用户选择是时,将显示“ headerWithYesNoChild” div。 如果选择“是”,则我希望要求用户选择其中一个复选框。 因此,我添加了以下自定义验证器:

jQuery.validator.addMethod("headerWithYesNo", function(value, element) {
    //If the value === no return valid
    if (value === 'no') return true;

    var yesNoChild = $(element).closest('.headerWithYesNo').children('.headerWithYesNoChild');
    var checkedInputs = yesNoChild.find('input:checked');

    //If any inputs are checked, return valid
    if (checkedInputs.length > 0) {
        return this.optional(element);
    }

    return false;
});

我使用以下JavaScript添加验证器:

$('.headerWithYesNo .choices input:radio').each(function () {
    $(this).rules("add", {
        headerWithYesNo: true,
        messages: {
            headerWithYesNo: "Make a selection from the options below or select 'No'"
        }
    })
});

我添加到我的validate函数的唯一选项是更改错误位置:

$('form').validate({
    errorPlacement: function(error, element) {
        ... error placement logic
    }
});

这很好用...有一个问题。 一旦选择“是”,就会在用户有机会进行选择之前触发验证。 我希望当用户选择“否”(清除所有失败的验证)或提交表单时触发验证。 我该如何实现?

我最终要做的是添加一个depends我的规则:

$('.headerWithYesNo .choices input:radio').each(function () {
    $(this).rules("add", {
        headerWithYesNo: {
            depends: function(element) {
                var targetType = $(event.target).attr('type');
                if (element.value === 'no' || targetType === 'submit') {
                    return true;
                }
                return false;
            }
        },
        messages: {
            headerWithYesNo: "Make a selection from the options below or select 'No'"
        }
    })
});

因此,如果无线电的值是“ no”,则将其设置为true。 或者,如果目标是提交输入。 但是我认为@Sparky对onclick提出了一些很好的建议,我只是想不出如何将其应用于仅一条规则。 我愿意就此提供更多反馈。

暂无
暂无

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

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