jQuery validation: Custom rule not called

五迷三道 提交于 2019-12-23 10:14:29

问题


Here is my simple validation code for testing:

    jQuery.validator.addMethod("oneTypeChecked", function (value, element) {
        return false; //$(':checkbox:checked') > 0
    }, "Check one or more type");

    $("#RequestCreateForm").validate({
        rules: {
            ChkBoxType1: { oneTypeChecked: true }
        }
    });

But my method oneTypeChecked is never called when I submit form. Why?

Here is my HTML code:

<div class="editor-field">
    <input type="checkbox" id="ChkBoxType2" name="requestTypeIds2" value="2">Type 2     
    <input type="checkbox" id="ChkBoxType1" name="requestTypeIds1" value="1">Type 1        
    <input type="checkbox" id="ChkBoxType3" name="requestTypeIds3" value="3">Type 3
</div>

Thank you very much!


回答1:


validation plugin works according to the name attribute and not id. try changing the name attribute on your input.




回答2:


with this html

<form id="RequestCreateForm" action="" method="post">
    <div class="editor-field">
        <input type="checkbox" class="oneTypeChecked" name="requestTypeIds2" value="2">Type 2     
        <input type="checkbox" class="oneTypeChecked" name="requestTypeIds1" value="1">Type 1       
        <input type="checkbox" class="oneTypeChecked" name="requestTypeIds3" value="3">Type 3
    </div>
    <input type="submit" value="submit" />
</form>

and this jquery

jQuery.validator.addMethod("oneTypeChecked", function(value, element) {
    return $('.oneTypeChecked:checked') > 0
}, "Check one or more type");

$("#RequestCreateForm").validate({
    rules: {
        ChkBoxType1: {
            oneTypeChecked: true
        }
    }
});

you will get the result you want

here is a WORKING DEMO




回答3:


As I understand it, if you don't add in the required it will be valid because it is not checked.

    rules: {   
        ChkBoxType1: { required : true, oneTypeChecked: true }
    }


来源:https://stackoverflow.com/questions/6019953/jquery-validation-custom-rule-not-called

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!