简体   繁体   中英

JQuery validate support for singular/plural forms

I am using JQuery Validate plugin and am using it to show localized error messages, like shown here https://jqueryvalidation.org/jQuery.validator.format/

Since i wanted to make it a library i localized the error messages like this

$.extend($.validator.messages, {
   min: $.validator.format("enter at least {0} number") // in other language
});

I would like it so that it supports plural form, so that i can have:

1) enter at least 1 number

2) enter at least 2 numbers

What is the best way to do this? I want to avoid manipulating the message outside the validate method.

Edit: typo

Use a function where you conditionally construct the message...

 $('#myform').validate({
        ....
        messages: {
            foo: {
                min: function(param) {
                    var plural = (param > 1) ? "s" : "";
                    return "enter at least " + param + " number" + plural;
                }
            }, ....

DEMO: jsfiddle.net/p82ojnj6/2/


Alternatively,

$.extend($.validator.messages, {
    min: function(param) {
        var plural = (param > 1) ? "s" : "";
        return "enter at least " + param + " number" + plural;
    }
});

DEMO 2: jsfiddle.net/p82ojnj6/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM