1

I am trying to use the JQuery Validation Plugin to do a client side form validation.

I build my form using css bootstrap. So I wan to use the help-block class to add has-error class to highlight the error. and where there is no error, I don't want to add any classes.

Here is what I have done

$('#myForm').validate({
    errorElement: "em",
    errorPlacement: function (error, element) {
        // Add the `help-block` class to the error element
        error.addClass("help-block");

        if (element.prop("type") === "checkbox") {
            error.insertAfter(element.parent("label"));
        } else {
            error.insertAfter(element);
        }
    },
    highlight: function (element, errorClass, validClass) {
        $(element).parents("div").addClass("has-error");
    },
    unhighlight: function (element, errorClass, validClass) {
        $(element).parents("div").removeClass("has-error");
    }
});

the problem with the above code is that when an error takes place all the field "valid or invalid" will get colored red. even if one field is not required it still gets highlighted.

How can I avoid adding the "red" color on the valid fields?

Jaylen
  • 39,043
  • 40
  • 128
  • 221

1 Answers1

0

Without knowing your exact css its hard to say, but I'm thinking it has to do with this line here: $(element).parents("div").addClass("has-error");

What this line is doing is going to the invalid element, then going to every div parent and adding the "has-error" class.

This means, every single input below a parent div of the invalid input will also be red if you have something like this in your css:

div.has-error input {
    background-color: red;
}

I would look to make your .parents('div') more specific, because the way it stands -- it goings all the way up the chain of parent elements that are divs. This is far too generic in my opinion.

Here is a rough illustration of what I mean. Basically, the invalid element isn't getting the class, instead ALL of its div parents are. That means if any of the children of these .has-error divs will have the error styling applied. enter image description here

Pat
  • 2,540
  • 1
  • 21
  • 28