designmode
designmode

Reputation: 163

Add Custom Error Condition and General Error Message for jQuery Validate Plugin

I am working on an in application solution for affords me limited page real estate and therefore cannot apply contained error messages for every required field. I therefore am trying to create a solution that would highlight the affected required fields and only create a custom message for specified fields like email address, telephone and password in my form.

I am presently working with the basic shell(which is working fine for contained messages)

    var v = $("form").validate({
        rules: {
            email: {
                required: true,
                email: true                 
            },
            confirmEmail: {
                required: true,
                email: true,
                equalTo: "#email"
            }
        },
        messages: {
            email: "Please enter a valid email address",
            confirmEmail: {
                required: "Please enter a valid verify email address",
                equalTo: "Both email addresses must be the same."
            }
        },
        errorContainer: errcontainer,
        errorLabelContainer: $("ol", errcontainer),
        wrapper: 'li',
        onkeyup: false,
        onblur: false
    });     

Thanks in advance for any help or advice.

Upvotes: 1

Views: 2569

Answers (1)

Ryley
Ryley

Reputation: 21216

What you want to do is implement the showErrors hook in the validate plugin.

You get passed a map of the error messages, and then an array of those same messages associated with the form element that produced them.

Your best bet is then to just take a copy of the default handler (called defaultShowErrors in the validate plugin) and modify it slightly (to only show labels for the ones you care about).

You'd then have something like this in your validate options:

showErrors: function(errorMap, errorList) {
    for (var i = 0; this.errorList[i]; i++) {
        var error = this.errorList[i];
        //this is the only real part you modify
        if (error.element.id == 'email' || error.element.id == 'confirmEmail') {
            this.showLabel(error.element, error.message);
        }
        this.settings.highlight && this.settings.highlight.call(this, error.element, this.settings.errorClass, this.settings.validClass);
    }
    //a whole bunch more stuff after this, from jquery.validate.js
}

See this idea in action here: http://jsfiddle.net/ryleyb/D3tfu/

Upvotes: 1

Related Questions