jQuery 如何使用 addClassRules 向类添加消息

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3247305/
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 15:07:19  来源:igfitidea点击:

How to add messages to a class with addClassRules

jqueryjquery-validate

提问by daddywoodland

I'm using jQuery Validateto validate a page with a large number of repeated rows of data. Due to limited space, each row has it's own validation summary.

我正在使用jQuery Validate来验证具有大量重复数据行的页面。由于空间有限,每一行都有自己的验证摘要。

I use addClassRules to apply the validation rules to the page but the default error messages are too generic in the summary (e.g. "Field is required, Field is required etc).

我使用 addClassRules 将验证规则应用于页面,但摘要中的默认错误消息过于通用(例如“需要字段,需要字段等)。

Example:

例子:

jQuery.validator.addClassRules({
amount: {
    required: true,
    range: [0, 2000000]
},
comment: {
    maxlength: 51
},
owner: {
    notFirstOption: true
},
A: {
    required: function (element) {  
        return getParentElement($(element), "tr").find(".colB input.B").val().length > 0;
    },
    digits: true
}});

Can you apply custom messages for the rules in each validation class? Ideally I'm after something like:

您可以为每个验证类中的规则应用自定义消息吗?理想情况下,我追求的是:

jQuery.validator.addClassMessages({
    amount: {
        required: "Amount is required",
        range: "Amount must be between 0 and 2,000,000"
    },
    comment: {
        maxlength: "Comment may be a maximum of 51 characters"
    },
    owner: {
        notFirstOption: "Please select an owner"
    },
    A: {
        required: "A is required if B is entered",
        digits: "A must be numeric"
    }});

Thanks in advance for any help you can offer!

在此先感谢您提供的任何帮助!

回答by Mark Holtman

In the documentation, the answer is to alias the method that you want to call and add the custom message.

在文档中,答案是为您要调用的方法添加别名并添加自定义消息。

Check the referenceunder the "Refactoring rules" heading:

检查“重构规则”标题下的参考

// alias required to cRequired with new message
$.validator.addMethod("cRequired", $.validator.methods.required,
"Customer name required");
// alias minlength, too
$.validator.addMethod("cMinlength", $.validator.methods.minlength, 
// leverage parameter replacement for minlength, {0} gets replaced with 2
$.format("Customer name must have at least {0} characters"));
// combine them both, including the parameter for minlength
$.validator.addClassRules("customer", { cRequired: true, cMinlength: 2 });

回答by Gowri

This can be done using below code,

这可以使用以下代码完成,

  $.validator.messages.accept = 'File must be JPG, GIF or PNG';

    $.validator.addClassRules("files", {            
      accept : "png|jpe?g|gif",  
      filesize : 2000000
    });

回答by daddywoodland

I've come up with a pretty heinous solution but hope for something a lot cleaner with a bit more time...

我想出了一个非常令人发指的解决方案,但希望能有更多时间更清洁的东西......

Anyway, by assigning the messages through jQuery metadata I'm able to customise them per class.

无论如何,通过通过 jQuery 元数据分配消息,我可以按类自定义它们。

class="amount {validate:
                {messages:
                  {required:'Amount is required',
                   range: 'Amount must be between 0 and 2,000,000',
                   digits: 'Amount must be numeric'}
                }
              }"

...and so on for each of the fields in my grid rows.

...等等我的网格行中的每个字段。

I'll be looking at extending the 'addClassRules' method to accept a messages parameter but for now this works so it'll do.

我将考虑扩展 'addClassRules' 方法以接受消息参数,但现在这可行,所以它会做。

回答by daddywoodland

Since everyone's obviously interested in the response to this one here's the next step in my pursuit of an answer!

由于每个人显然都对对此的回应感兴趣,这是我寻求答案的下一步!

I've added methods into the plugin that allow the addition of class messages and amended the default message handler to pick these out.

我已经在插件中添加了允许添加类消息的方法,并修改了默认消息处理程序以选择这些。

Added before 'customMetaMessage'

在“customMetaMessage”之前添加

customClassMessage: function (element, method) {
    //Get the elements class(es)
    var classes = $(element).attr("class").split(" ");

    //return any message associated with said class and method
    var m = $.validator.messages[classes[0]];

    return m && (m.constructor == String
        ? m
        : m[method]);
},

Amended 'defaultMessage' to include a call to the above method

修改了“defaultMessage”以包含对上述方法的调用

defaultMessage: function (element, method) {
                return this.findDefined(
                this.customMessage(element.name, method),
                this.customMetaMessage(element, method),
                this.customClassMessage(element, method),
                // title is never undefined, so handle empty string as undefined
                !this.settings.ignoreTitle && element.title || undefined,
                $.validator.messages[method],
                "<strong>Warning: No message defined for " + element.name + "</strong>"
            );
            },

Added an 'addClassMessages' method

添加了“addClassMessages”方法

        addClassMessages: function (className, messages) {
        if (className.constructor == String) {
            $.validator.messages[className] = messages != undefined ? messages : $.validator.messages[className];
        }
        else {
            $.extend(this.messages, className);
        }
    },

I haven't been able to work out how to attach these additional methods outside of the plugin as yet. At least I don't have to declare error messages in the 'class' attribute though.

我还没有弄清楚如何在插件之外附加这些额外的方法。不过,至少我不必在 'class' 属性中声明错误消息。

jQuery.validator.addClassMessages({
    amount: {
        required: "Amount is required",
        range: "Amount must be between 0 and 2,000,000",
        digits: "Amount must be numeric"
    }
});

回答by Irfan Ashraf

Use data-msg-required="Error message here"with the element you like to do validation

data-msg-required="Error message here"与您喜欢进行验证的元素一起使用

<select name="account1" data-msg-required="Please select an account">
<option value="">--Select Account--</option>
<optgroup label="100-Assets">
    <option value="1">A</option>
    <option value="2">B</option>
    <option value="3">C</option>
    <option value="4">D</option>
</optgroup>

回答by Martin Karlsson

Try this:

尝试这个:

jQuery.validator.addClassRules({
    amount: {
        required: true,
        range: [0, 2000000],
        messages: {required: "Required field!", range: "Invalid range!"}
    },
    comment: {
        maxlength: 51,
        messages: {maxlength: "Max 51 characters!"}
    }
})

I think that is what you are looking for, correct?

我想这就是你要找的,对吗?