在 jQuery Validate 中创建自定义规则

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17561615/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 19:18:52  来源:igfitidea点击:

Creating a custom rule in jQuery Validate

javascriptjqueryvalidation

提问by Jason Wells

I would like to add a custom rule to jQuery validate, and while I have checked the docs I have not been able to find out how to do this.

我想向 jQuery 验证添加自定义规则,虽然我已经检查了文档,但我无法找到如何执行此操作。

I want to loop over a set of hidden form fields. If the fields value is "X", then I would like to append an error class to a field.

我想遍历一组隐藏的表单字段。如果字段值为“X”,那么我想将错误类附加到字段。

So essentially this, but added as a rule to jQuery validate.

所以本质上是这样,但作为规则添加到 jQuery 验证中。

$(".myHiddenField").each( function() {
   if($(this).val() == "x") {
    $(this).closest(".foo").appendClass("error");
   }
});

回答by Nikko Reyes

You may use addMethod()

您可以使用 addMethod()

$.validator.addMethod('yourRuleName', function (value, element, param) {
    //Your Validation Here

    return isValid; // return bool here if valid or not.
}, 'Your error message!');


$('#myform').validate({
    rules: {
        field1: {
            yourRuleName: true
        }
    }
});

回答by Arun P Johny

If you want to show some custom error messages without adding an actual rule then you can use the showErrors()method, but if you are working on a hidden field it may not work

如果您想在不添加实际规则的情况下显示一些自定义错误消息,则可以使用showErrors()方法,但如果您正在处理隐藏字段,则它可能不起作用

var validator = $( "<form-selector>" ).validate();

var errors = {};
$(".myHiddenField").each( function() {
    var $this = $(this);
    if($this.val() == "x") {
        errors[$this.attr('name')] = 'Some error message';
    }
});

validator.showErrors(errors);

回答by areschen

$.validator.addMethod("NOTx", function(element,value) {
    return  value != "x";
}, 'warning word"!');