Event hooks for MVC unobtrusive remote validation
G

2

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.

Georgetta answered 2/5, 2012 at 12:57 Comment(0)
D
7

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

$.validator.setDefaults({
    onkeyup: false,
    onfocusout: false,
    onsubmit: true
});
Disappearance answered 2/5, 2012 at 13:3 Comment(5)
Doesn't overriding the default settings affect other forms? Or does setting the defaults only scope to the currently loaded page?Georgetta
Only the scope of the currently loaded page.Disappearance
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"?Georgetta
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.Disappearance
how do we restrict this defaults to some fields say(zipcode)?Timecard
T
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;
});
Thies answered 15/9, 2016 at 13:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.