I am using the jQuery validation plugin (http://docs.jquery.com/Plugins/validation). The form which is being validated has custom background images for the text input fields, so instead of showing an error message for invalid fields I would like to change the background image. Making things a bit trickier is that the background image for the fields is on a different div
absolutely positioned behind the text field (which has a transparent background and no border). I will spare going into the reasons for this design decision here (it's related to margins within the text field) but I thought it should be mentioned since it is critical to this question.
Therefore, I have two questions:
How can I stop the display of the error messages all-together?
How can I instead tell the validation plugin if, for example, the name field (e.g. <input id=name ... />
) is invalid then it should change the background for the relevant div (e.g. <div id=name-bg... ></div>
)?
Thanks for any assistance!
How can I stop the display of the error messages all-together?
You can accomplish this by using the showErrors
option of the validate plugin:
$("#commentForm").validate({
showErrors: function(errorMap, errorList) {
/* Custom error-handling code here */
}
}
});
The errorList
argument is a list of objects, each containing an element
property that is the DOM element with the error.
How can I instead tell the validation plugin if, for example, the name field is invalid then it should change the background for the relevant div?
Using the showErrors
option and the errorList
argument detailed above, you could accomplish this like this:
$("#commentForm").validate({
showErrors: function(errorMap, errorList) {
var i, length = errorList.length;
var el;
for (i = 0; i < length; i++) {
el = errorList[i].element;
/* Build up a selector based on the element containing and error's id:*/
$("#" + el.id + "-bg").show() // <-- write code against this selector
}
}
});
Here's a proof-of-concept: http://jsfiddle.net/vD5cQ/
Hope that helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With