Inserting an element within jQuery Validation plugin's error template

Posted by simshaun on Stack Overflow See other posts from Stack Overflow or by simshaun
Published on 2011-01-13T06:44:28Z Indexed on 2011/01/16 9:53 UTC
Read the original article Hit count: 237

I'm utilizing the jQuery Validation plugin for my form. It lets you change the errorElement and wrap the errorElement using with the wrapper option. But, I want to insert an element within errorElement like this:

<label class="error"><em></em>Error message goes here</label>

Is there an easy way to accomplish inserting the em tag?


I've tried prepending the em tag using the errorPlacement option (see below), but it seems the plugin is replacing the contents of errorElement afterwards.

$.validator.setDefaults({
    errorPlacement: function(error, element) {
        error.prepend('<em/>');
        error.insertBefore(element);
    }
});


I've also tried prepending the em tag using the showErrors option (see below). Again, it seems the plugin is replacing the contents of errorElement afterwards.

$.validator.setDefaults({
    showErrors: function(errorMap, errorList) {
        for (var i = 0; i < errorList.length; i++) {
            var error = errorList[i],
                $label = this.errorsFor(error.element),
                $element = $(error.element);

            if ($label.length && $label.find('em').length == 0) {
                $label.prepend('<em/>');
            }
        }

        this.defaultShowErrors();
    }
});


I've also tried modifying the plugin so that when the error element is generated, the <em> tag is prepended. That works until I focus on a form element that has an error, after which the em tag is removed. (It's doing this because jQuery validation is constantly updating the contents of the error element as I focus and/or type in the field, therefore erasing my em tag added at error-element creation.)

© Stack Overflow or respective owner

Related posts about jQuery

Related posts about jquery-plugins