Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
476 views
in Technique[技术] by (71.8m points)

jquery - How to add messages to a class with addClassRules

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

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).

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

Check the reference under 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 });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...