Is it possible to “hack into” the unobtrusive vali

2019-05-13 23:04发布

问题:

I want to be able to use the built-in, data-annotation based, client-side unobtrusive validation, but do my own ajax form submission after I know it passes.

Something like this jQuery bit:

$('#form').submit(function(e) {
  e.preventDefault();

  if (PassesUnobtrusiveValidation()) {
    // ajax submit form
  }
});

Is there a PassedValidation event, or something like it, (built into the default, asp.net mvc 3 data-annotation based client side validation) I can hook into (like the psuedocode in the example)?

I want to do this so I can still take advantage of the data-annotation based validation, and then submit the form asynchronously how I want to. I wish to avoid writing common validation in the client, letting asp.net mvc 3 take care of it for me, and then submitting the form how I want to, using $.ajax();

回答1:

If you are using jquery.validate:

$('#myForm').submit(function() {
    if ($(this).valid()) {
        // Client side validation passed => submit the form
    }
});

Another possibility is to hook at the plugin options:

$.validator.setDefaults({
    submitHandler: function(form) {
        // Client side validation passed => submit the form
    }
});

If you are using MSAjax then good luck with this.