Inserting an element within jQuery Validation plugin's error template
- by simshaun
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.)