Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to clear error when using jquery validate and custom errorPlacement

I am using jquery and validate to validate my form. Instead of adding an element to the missing field I am adding a border to the element using this option errorPlacement

$("#signup-form").validate({
       submitHandler: function(form) {
      form.submit();
   },
   errorPlacement: function(error, element) {
      element.css("border", "solid 1px red");
   }                    
});

the one thing i can not seem to figure out is how to clear it when valid?

So I started with the above code. Then tried and i am confused with the results. If I do not have the success: option when a field fails it adds the class successfully. But as soon as I add the success option all the required fields are getting that class, and if I inspect the element I see <input class="required invalid valid"> so I am doing something incorrectly.

           $("#signup-form").validate({
                submitHandler: function(form) {
                    // do other stuff for a valid form
                    //form.submit();
                },
                errorPlacement: function(error, element) {
                    element.addClass("invalid");
                },        
                success: function(error) {
                    // change CSS on your element(s) back to normal
                },                    
                 debug:true
            });
like image 867
randy Avatar asked Aug 28 '12 15:08

randy


1 Answers

You could try adding this to your list of .validate() options...

success: function(error) {
    // change CSS on your element(s) back to normal
}

This should work dynamically without a form submit. As soon as the error is resolved, the contained code will run.

See documentation.

Please create a demo of your problem using jsFiddle. Here's a blank jsFiddle with .validate() already included and ready for use.


EDIT

As per OP's jsFiddle, I made these changes...

    errorPlacement: function(error, element) {
        $(element).filter(':not(.valid)').addClass("invalid");
    },
    success: function(error) {
        console.log(error);
        $("#signup-form").find('.valid').removeClass("invalid");
    }

Working Demo: http://jsfiddle.net/u3Td3/6/

Side-notes: You also had some HTML issues. You should "self-close" your input elements with />. Same thing for the submit button, self-close rather than using a </input>. See validator.w3.org to validate your HTML. I'd also not use a table for layouts, use CSS.

like image 183
Sparky Avatar answered Sep 28 '22 08:09

Sparky