chainwork
chainwork

Reputation: 2886

jQuery Validate - How to remove a class for error on a specific label?

See problem in action here: (Kudos to anyone who can help!)

http://jsfiddle.net/74u7g/

The required text remains green (class not removed) if the user later changes their entry (after success) causing an error. How do I successfully remove class checkMark on error?

$("#registerForm").validate({       
    rules: {
    createUsername: {
    required: true,
    email: true
},

    createPassword: {
    required: true,
    minlength: 6
    },

    createPassword2: {
    equalTo: "#createPassword",
    minlength: 6
    }
},

messages: {
    createPassword: {
    required: "This field is required.",
    minlength: "Password must be 6-15 characters long."
    }
},

success: function(label) {
    if ( $(label).parent().is('#confirmPassContainer') ) {
        $(label).addClass('checkMark').html('✓'); 
        }   
    }

});

I've tried the highlight and error methods with no success. I've searched high and low for an answer on StackOverflow but no luck yet. Hoping for a solution using jQuery.

Upvotes: 2

Views: 4338

Answers (2)

Sparky
Sparky

Reputation: 98718

Use highlight: inside your .validate()...

highlight: function (element, errorClass) {
    $(element).siblings('label').removeClass('checkMark');
}

I believe it will fire every time the form tests invalid... kinda works the opposite of success:.

Inside your demo:

http://jsfiddle.net/74u7g/5/

EDIT:

element refers to the specific input element that is being validated.

errorClass refers to the class that the plugin is using to flag errors. Not used within this example.

So $(element) selects the element with the error, then .siblings('label') selects only the siblings that are <label> elements, then .removeClass('checkMark') removes your checkMark class.

$(element).siblings('label').removeClass('checkMark');

EDIT 2:

You may want to add a conditional that tests to see if it's on the relevant input element, although I'm sure it certainly won't hurt to let it run on all of the elements.

See: http://jsfiddle.net/74u7g/6/

if ( $(element).parent().is('#confirmPassContainer') ) {
    $(element).siblings('label').removeClass('checkMark');
}

Upvotes: 2

MatRt
MatRt

Reputation: 3534

you can fix the problem by using CSS priority.

.regForms .error {
    display:block;
    color:#c92a00 !important;
    font-size:12px;
}

In your case, when the 2nd password is not the same as the first, you have 2 CSS rules at the same time with 2 color definition. !important allow you to give priority to the error one.

Upvotes: 1

Related Questions