2

I have a form that Im validating with jQuery validate pluging.

This is my jQuery code for validating:

$('#authForm').validate({
                rules: {
                    Email: {
                        required: true,
                        email: true
                    },
                    Password: {
                        required: true
                    },
                    PasswordAgain: {
                        equalTo: "#Password"
                    },
                    Name: {
                        required: true
                    }
                },
                errorClass: "invalid",
                errorPlacement: function(error, element) { }
            });

I have added an errorClass that I need to append to a parent div, not to the input field:

The HTML structure of one of the fields are like this:

<div class="form-group form-group-custom ">
    <label>Email Address</label>
    <input name="Email" type="text" class="form-control invalid" value="[email protected]" aria-required="true" aria-describedby="Email-error" aria-invalid="true">
</div>

And if you notice the "invalid" class has been appended to the input element that actually is correct, but I need to append it to my <div class="form-group form-group-custom"> and also remove it when the validation is ok.

1 Answer 1

2

The highlight and unhighlight functions are always used to apply/remove any classes when things go valid/invalid. Simply write custom jQuery DOM traversal functions that target your parent div.

$('#authForm').validate({
    rules: {
        ....
    },
    ....
    highlight: function(element, errorClass, validClass) {
        $(element).parent('div').addClass(errorClass).removeClass(validClass);
    },
    unhighlight: function(element, errorClass, validClass) {
        $(element).parent('div').addClass(validClass).removeClass(errorClass);
    },
    ....

If the classes need to be completely separate from the classes that are automatically applied by the plugin, then instead of using the keywords that represent the pre-set classes, use different classes renamed as you wish.

    highlight: function(element, errorClass, validClass) {
        $(element).parent('div').addClass('myerrorclass').removeClass('myvalidclass');
    },
    unhighlight: function(element, errorClass, validClass) {
        $(element).parent('div').addClass('myvalidclass').removeClass('myerrorclass');
    },
Sign up to request clarification or add additional context in comments.

Comments

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.