簡體   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