jQuery Validation Callback Function
Asked Answered
K

2

8

I currently have a form within a lightbox frame on my webpage. When a user submits the form with invalid data, a div appears with a list of form errors at the top of the form. The problem is: I need some sort of jQuery validation callback to resize the lightbox after the errors div appears. As far as I'm aware, there is no way to do this with the jQuery lightbox.

Knowledge answered 3/6, 2011 at 8:20 Comment(1)
Do you mean a lightbox iframe? Are you validating the form using a plugin or your own script?Katalin
I
22

you to supply the invalid callback function which you can find documented here, like so

$(".selector").validate({
    invalidHandler: function(form, validator) {
        var errors = validator.numberOfInvalids();
        if (errors) {
            //resize code goes here
        }
    }
})
Immorality answered 3/6, 2011 at 20:55 Comment(2)
I guess it didn't occur to me to handle all the error display and placement within the invalidHandler function. Thanks!Knowledge
how would you attach this handler after the .validate has already been initialized/called?Visitor
G
4

Alternatively, you can use the errorPlacement callback function in order to act on the specific element that failed validation. As an example, the code below uses the errorPlacement callback to set the class of each invalid form element's parent div tag to "error" and then removes the "error" class once the element passes validation :

form.validate({
        rules: {
            Name: {
                required: true
            },
            Email: {
                required: true
                , regex: "^[0-9a-zA-Z.+_\-]+@{1}[0-9a-zA-Z.+_\-]+\\.+[a-zA-Z]{2,4}$"
            }
        },
        messages: {
            Name: {
                required: "Please give us your name"
            },
            Email: {
                regex: "Please enter a valid email address"
            }
        },

        errorPlacement: function(error, element) {
            element.parent().addClass("error");
        },

        success: function(element) {
            $("#" + element.attr("for")).parent().removeClass("error");
        }
    });
Gardal answered 19/3, 2016 at 0:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.