haagel
haagel

Reputation: 2726

Catch that a form is not posted to the server due to validation errors

I have a basic ASP.NET MVC form with validation. The validation is implemented using attributes/data annotations in the viewmodel, and my website is configured so that validation is performed both on the client side and on the server side. A very common pattern I believe.

The form is submitted using an ordinary postback; there so no ajax involved.

Sometimes processing the form takes some time, so I want to show a spinner while the processing takes place. I've implemeted the necessary code to show and hide a spinner using javascript.

I use jquery to show the spinner when the form is submitted.

$('form').submit(function () {
     showSpinner();
});

The spinner is shown and if everything went well the page is refreshed and thus the spinner disappears. No need to call my hideSpinner() javascript function.

The problem is that if there's a validation error in the form the spinner will still be shown but there will be no page refresh since the client side validation will stop that from happening. Therefore the spinner will not disappear.

I've tried solving this by manually hiding the spinner like this:

$('form').bind('invalid-form.validate', function () {
    hidespinner();
});

Using this code the spinner is actually hidden but it also seem to disable the client side validation! No validations messages are shown and the page is refreshed, even if there are errors.

Is there a better way to show the spinner only when the form is actually submitted to the server, or to hide the spinner if the client side validation stops the form from being posted?

Upvotes: 1

Views: 492

Answers (1)

user3559349
user3559349

Reputation:

You can test if the form is valid using the .valid() method

$('form').submit(function () {
    if($(this).valid()) {
        showSpinner();
    }
});

Upvotes: 3

Related Questions