5

Is there a way to hook into MVC3 unobtrusive remote validation on the client, before data is submitted to the remote method, and after a result is returned from the remote method?

I am trying to tell a remote validator to only perform validation if the submit button is clicked. The normal behavior is to validate several times, such as during keypress, blur etc. This is no good, as the validation method in question needs to call a non-idempotent operation. I need to make sure that method is only invoked if the user has clicked the submit button.

If I could hook into a before event, I could set a field in the form that flags the submit button as being clicked or not. However I would need to reset this flag after the remote method returns a validation result.

Any other suggestions? This is for validating a password using the ASP.NET Membership Provider's Membership.ValidateUser(string username, string password) method. This method will increment the FailedPasswordAttemtCount each time an invalid password is sent, so I don't want it to execute during blur, keypress, etc.

danludwig
  • 46,965
  • 25
  • 159
  • 237

2 Answers2

7

You could override the default validation options for the current page:

$.validator.setDefaults({
    onkeyup: false,
    onfocusout: false,
    onsubmit: true
});
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Doesn't overriding the default settings affect other forms? Or does setting the defaults only scope to the currently loaded page? – danludwig May 02 '12 at 13:04
  • Only the scope of the currently loaded page. – Darin Dimitrov May 02 '12 at 13:07
  • This really is the best solution, thanks. Just to satisfy my curiosity, is the answer to my question "There aren't any" or "It isn't easy"? – danludwig May 02 '12 at 13:18
  • There aren't any with the ASP.NET MVC unobtrusive scripts. If you were using the plain jQuery.validate plugin then you could manually specify the options passed to the AJAX call => so you could subscribe to the `onbeforesend` and the `complete` callbacks. – Darin Dimitrov May 02 '12 at 13:27
  • 1
    how do we restrict this defaults to some fields say(zipcode)? – ashraf Dec 29 '12 at 21:16
0

The solution above didn't resolve this for me. Somehow, the validator setting was not being set. So, I implemented the following and it worked:

$(function () {
    var settings = $.data($('form')[0], 'validator').settings;
    settings.onkeyup = false;
});
Ozzy
  • 964
  • 1
  • 10
  • 21