2

I have the following code which adds custom css styles to my form when using the jQuery validation plugin.

$(document).ready(function() {
    jQuery.validator.setDefaults({
        errorPlacement: function(error, element) {

        // Adds the red outline
        element.parent().addClass("error");

        // Adds the red cross
        element.siblings(".error_status").addClass('check');

        // Removes the default error
        element.removeClass("error");
        }       
    });

 $("#form").validate();

});

Which styles the following html for each element:

<div class="row">
    <label for="id-3"><span>Email address:</span><span class="mark">*</span>
    <input type="text" class="text required" id="id-3" name="email"/>
    <span class="error_status"></span>
</div>

The problem I'm having is that I don't know how to subsequently remove the styles after a successful validation.

1
  • What do you mean with "remove the styles after a successful validation"? After a successful validation the data is sent to the server. Can you provide an example on jsFiddle.net? Commented Dec 23, 2011 at 11:07

1 Answer 1

3

You might want to use the highlight and unhighlight callbacks (documented here) instead of errorPlacement. This way, you won't have to manually remove the error class from the element:

jQuery.validator.setDefaults({
    highlight: function(element, errorClass) {
        var $element = $(element);
        // Add the red outline.
        $element.parent().addClass(errorClass);
        // Add the red cross.
        $element.siblings(".error_status").addClass("check");
    },
    unhighlight: function(element, errorClass) {
        var $element = $(element);
        // Remove the red cross.
        $element.siblings(".error_status").removeClass("check");
        // Remove the red outline.
        $element.parent().removeClass(errorClass);
    }
});
Sign up to request clarification or add additional context in comments.

2 Comments

Excellent that fixed it. However it seemed that element wasn't an element object but just the html? I fixed this by putting $(element).sib... rather than just element.sib
You're right, the callbacks are indeed called with a DOM element and not a jQuery object. Answer updated accordingly, thank you for your feedback :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.