jQuery Validation plugin: add/remove class to/from element's error container
Asked Answered
S

2

14

I'm working with the jQuery Validation plugin and I wrote the following code which adds a class to the element's (<input>) parent (<label>) if not valid, as well as inserting the actual error element (<span>) before the <br>.

the HTML ...

<label>
    text<br><input>
</label>

... and the jQuery.

$("#form_to_validate").validate({
    rules: {
    ...
    },
    errorElement: "span",
    errorPlacement: function(error, element) {
        element.parent().addClass('error');
        error.insertBefore(element.parent().children("br"));
    }
});

So, if a form element doesn't validate, it turns into:

<label class="error">
    text<span>error text</span><br><input>
</label>

This works great, however, if a field's content is corrected and becomes valid, the class obviously doesn't get removed from its parent (actually, neither does the error element, instead it just gets a display: none; CSS property). How can I check if an element becomes valid and remove its parent class if so ?

Any help would be greatly appreciated !


Edited: Added more information.

Schaab answered 24/3, 2010 at 2:58 Comment(0)
S
30

After some more heavy digging I found the answer right under my nose, but unfortunately for me, well hidden. The plug-in has a built-in highlighting function (surprise, surprise). Normally it would highlight/unhighlight the element, but it can easily be converted to work on the element's parent:

$("#form_to_validate").validate({
    rules: {
    ...
    },
    errorElement: "span",
    errorPlacement: function(error, element) {
        error.insertBefore(element.parent().children("br"));
    },
    highlight: function(element) {
        $(element).parent().addClass("error");
    },
    unhighlight: function(element) {
        $(element).parent().removeClass("error");
    }
});

I hope this will help someone !

Schaab answered 24/3, 2010 at 5:13 Comment(0)
L
0

errorElement: 'none' worked for me.

Livy answered 18/9, 2010 at 13:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.