views:

30

answers:

1

Using the errorPlacement hook I am able to add a certain class to a certain error element. However once the form has attempted to submit the second time, it looses that class I added. See the following code for the example.

http://www.jsfiddle.net/NU63P/1

How can I keep that additional class on the element through the entire life-cycle of the validation process? Is there another hook where I need to add the class back? Ultimately what I'm trying to accomplish is I want to add a specific class to just second text box error label.

+2  A: 

Unfortunately there's not a straight-forward way to do this provided by the API because it made (in my opinion) a bad decision here:

showLabel: function(element, message) {
  var label = this.errorsFor( element );
  if ( label.length ) {
    label.removeClass().addClass( this.settings.errorClass );
                   //^ right here
  }

This is what's removing all your classes, and unfortunately it's also the last thing to run in the invalid handler pipeline. However, it's called by defaultShowErrors() which you can call yourself by overriding the showErrors option, like this:

$(function() {
  $('form').validate({
    showErrors: function(errorMap, errorList) {
      this.defaultShowErrors();
      $(this.currentForm).find('label[for=text2].error').addClass('errorextra');
    }
  });
});

You can test it out here.


The other option, if you're only supporting newer browsers would be to do this completely in CSS:

label[for=text2].error { margin-left: 10px; }
Nick Craver
exactly what i was looking for thanks man
aherrick