jquery验证器addmethod自定义消息

tim*_*den 18 validation jquery

我已经为jquery的验证器插件创建了一个方法,它的工作方式类似于远程规则.不同之处在于我想显示动态错误消息(基于ajax响应).

jQuery.validator.addMethod("duplicate", function(value, element, params) { 
    var object_settings = this.settings;
    params.data[$(element).attr("name")] = value;
    $.post(params.url, params.data, function(response) {
        if (response == 'true'){ return true; }
        else {
            object_settings.messages[element.name] = response;
            return false;
        }
    }, 'text');
}, '');
Run Code Online (Sandbox Code Playgroud)

它工作......有点....它设置消息,但最初不显示它(如果你第二次验证字段,则显示消息).

有什么建议?

(也许远程规则提供此功能......我在文档中找不到任何内容)

tim*_*den 15

这是解决方案....需要调用对象的showErrors函数:

jQuery.validator.addMethod("duplicate", function(value, element, params) { 
    var validator = this;
    params.data[element.name] = value;
    $.post(params.url, params.data, function(response) {
        if (response == 'true'){ return true; }
        else {
            var errors = {};
            errors[element.name] =  response;
            validator.showErrors(errors);
            return false;
        }
    }, 'text');
}, '');
Run Code Online (Sandbox Code Playgroud)

取自jquery.validate.js中的"remote"(第917行 - 第919行)

  • 执行此操作时,默认错误消息是写入自定义消息. (4认同)

jsh*_*erk 9

正在寻找解决方案,并发现这...

在原始示例中,如果更改此行:

object_settings.messages[element.name] = response;
Run Code Online (Sandbox Code Playgroud)

对此:

$.validator.messages.duplicate = response;
Run Code Online (Sandbox Code Playgroud)

这适合我.我在这里找到了它:http: //blogs.teamb.com/craigstuntz/2009/01/15/37923/


Kir*_*ran 7

我已经按照网站http://blogs.teamb.com/craigstuntz/2009/01/15/37923/#comment-125774中提到的流程进行了操作并成功完成了.

您必须使用动态消息调用该方法,以便它将显示该消息.例如

$.validator.addMethod("validatePremium", function(value, element, param) {

    if( Condition )    

     {
       $.validator.messages.validatePremium = "your message here";
       //enter code here
       //...
       return false;
     }

    }, $.validator.messages.validatePremium);
Run Code Online (Sandbox Code Playgroud)

  • 对我来说最好的答案,用魅力解决我的问题:链接:https://codepen.io/plasebo/pen/VGaQam 谢谢 Kiran (2认同)