开发者

How to add messages to a class with addClassRules

开发者 https://www.devze.com 2023-01-07 20:11 出处:网络
I\'m using jQuery Validate to validate a page with a large number of repeated 开发者_JAVA技巧rows of data.Due to limited space, each row has it\'s own validation summary.

I'm using jQuery Validate to validate a page with a large number of repeated 开发者_JAVA技巧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!


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 });


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
    });


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.

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.


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'

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

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


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

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


The suggested answers requires to write custom method or common error messages, which sometimes not easily customised. Below one works for me which was mentioned in github issue tracker:

$.validator.addClassRules = function (className, rules) {

    if (className.constructor === String) {
        var obj = {};
        obj[className] = rules;
        className = obj;
    }

    $.each(className, function (n, r) {
        $("." + n).each(function (i, e) {
            var self = $(e)
            self.rules('add', r);
        });
    });

}

Usage:

$.validator.addClassRules({
    'firstname': {
        required: true,
        messages: {
            required: "First name is required"
        }
    }
});


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?

0

精彩评论

暂无评论...
验证码 换一张
取 消