I have a senario where i have to check for a Username existance in database while doing a registration page. for this i have implemented a Remote Attribute for remote validation in my model
[Remote("CheckUserNameAvaliable", "User", Httpmethod="Post")]
public string Username {get; set;}
and my method looks like this
[HttpPost]
public JsonResult CheckUserNameAvaliable(string UserName)
{
SessionUser currentUser = this.sessionHelper.GetCurrentUser();
User user = this.userService.GetByUsername(UserName);
if (user != null && user.Id != currentUser.Id)
{
return Json(false);
}
return Json(true);
}
It works fine for me, but the problem is that whenever we made a key up on the username Textbox it will file this remote validation, but according to my requirement i have to fire this remote validation only after entering value in the username Textbox. For that can we forcefully add a delay to the remote validation attribute?
Do anyone know how to add delay to remote validation in MVC3?
I have been caught on similar problems before with MVC3 and remote validation. Guess you want the event to fire on blur but not sure how you'd tell the remote validation that..
Hopefully this will help
ASP.NET Remote Validation only on blur?
MVC3 uses the jquery.validate plugin in the browser. With jquery.validate, field validation doesn't start until the first change and blur of the field, or upon submit if the field wasn't touched.
Once field validation starts for a field, the onkeyup setting of the validator controls whether validation is performed on each keyup event. If you're performing remote validation on a field with every key press it's probably sending too many ajax messages stressing both the client and server.
As the other responders mentioned, you can suppress the keyup validation by setting validator.settings.onkeyup = false, but that suppresses onkeyup validation on all form fields, not just those with a remote validation rule. What I suggest is that you suppress keyup while the field with remote validation has focus and then turn it back on when you blur the field.
Suppressing onkeyup is easy. The problem is that changing the setting from false to true does not turn the feature back on. To turn it back on you need to set it to the function defined in the defaults of the $.validator object.
Here's the javascript code to include on your page if you're using MVC unobtrusive validation. It will cover all forms on your page. And be sure to use jquery.validate version 1.9.0 or later 'cause earlier versions don't work properly with IE 7 or 8 (yeah, I have to support those users too):
$("form input[data-val-remote-url]").on({
focus: function () {
$(this).closest('form').validate().settings.onkeyup = false;
},
blur: function () {
$(this).closest('form').validate().settings.onkeyup =
$.validator.defaults.onkeyup;
}
});
If you don't want to validate on keyup but on blur then this is what you want