BattlFrog
BattlFrog

Reputation: 3397

How to tell, in code, if form failed validation (client side)

I am building an mvc app with jquery.validate, jquery.validate.unobtrusive etc.

I have a function I want to execute onclick of the submit button if the form is invalid, so I have been looking for a variable or flag or something that gets set on the client side when the validation fails, so I can fire my function based on that, but I have not been able to find anything that will work. Anyone know of a global "Failed-Validation" variable in one of the jquery scripts? Or is there a function in the jquery validate stuff that would have that info?

Upvotes: 0

Views: 56

Answers (1)

B2K
B2K

Reputation: 2611

Here's what I do to hook into the client side validation. When a failure occurs, the user is prevented from posting the page, but I needed to log this on the server. You could easily replace the logJsError method with code of your choosing.

    $(window).load(function () {
        $('form').bind('invalid-form.validate',
            function (form, validator) {
                var message = $.map(validator.errorList, function (error) {
                    return error.message;
                }).join("\r\n");
                if (message) {
                    logJsError(message);
                }

            }
        );
    });
    function logJsError(message) {
        $.get('@page.Url.Action("Index", "Postback")[email protected]["controller"]&[email protected]["action"]&message=' + encodeURIComponent(message) + '&ts=' + (new Date().getTime()));
    }

Upvotes: 1

Related Questions