MVC 3: running javascript after validation has com

2019-05-02 00:45发布

问题:

Folks,

I have an MVC3 data entry form scenario that involves asking the user to confirm something after client-side validation has been satisfied, but before the post to the server.

Is there a way to insert some javascript into the sequence of events after the validation framework gives the go-ahead to post back, but before the post back happens?

(And of course if the user declines the confirmation, the post back has to cancel, too. )

Many thanks.

回答1:

You could subscribe for the .submit event of the corresponding form and check if it is valid:

$(function() {
    $('form').submit(function() {
        if ($(this).valid()) {
            // client validation passed successfully
        } else {
            alert('there was an error during client validation');
            // cancel the submission of the form
            return false;
        }
    });
});

or if you don't want to subscribe for the submission of the form and you want to verify if client validation passes for a given form you could always check like this:

var isValid = $('#someFormId').valid();