JQuery Validator- Rule specific errorPlacement
Asked Answered
P

1

6

I'm using jquery validator.

I've got a custom rule applied to a group of elements in my form. These inputs may also have other (standard) rules associated with them. I need to place the error message in one place if the element fails my custom rule, but another place if the element fails a standard rule.

I need something like -

errorPlacement: function(error, element) {
    if (error == MyCustomError) {
        // put my error at the top of the form
    } else {
        // put my error next to the element
    }

I can't see what that 'error' object really is (tried drilling down with firebug but it wasn't very informative).

The highlight option is even more difficult because I don't even have the 'error' parameter to use.

Predictor answered 26/4, 2012 at 14:1 Comment(0)
D
9

error is the whole error label HTML element that is being added by jQuery Validate, i.e.:

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

So if you want to place the message differently if the message is "Do not do this", you can:

errorPlacement: function(error, element) {
if (error.text() == "Do not do this") {
    error.insertBefore("SELECT FIRST ELEMENT IN THE FORM HERE USING STANDARD JQUERY SELECTORS");
} else {
    error.insertAfter(element);
}
Dowzall answered 1/11, 2012 at 15:59 Comment(4)
This will only work if you are working with single language. Any idea how to get the rule type instead?Jermyn
jQuery Validate doesn't provide the rule type by default in the errorPlacement method. But you have the element, so you can do: element.data('rule') and assign the data-rule="required" for example straight on the element in your HTML. That way you can use that once you need to put the error messages. Let me know if that helps!Dowzall
Thanks for getting back tome, @Smilyan. That sounds like a valid path to take. In my particular use case, I ended up creating hidden input with the jQuery validator data attributes injected by the controller, so on client side, I just added keyup event to modify value + trigger validation for that hidden input.Jermyn
I personally have created a wrapper class around the whole jQuery validate. That way I can put on any form .validate-form class to start validating and then for each method that I wish I add a class on the input for example .validate-min-length with data-attributes data-min-length="20". Then you can use those classes in your errorPlacement method and know that they are used for that (and you can have more than 1 validation method as well). That way I don't need to repeat code at all and just use classes for any new forms.Dowzall

© 2022 - 2024 — McMap. All rights reserved.