Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 688
Valentin Flachsel Avatar asked Mar 24 '10 02:03

Valentin Flachsel


1 Answers

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 !

like image 142
Valentin Flachsel Avatar answered Sep 18 '22 13:09

Valentin Flachsel