TopMenu

Customize Unobtrusive Jquery validation trigger

Sometime it’s required to change a default behavior of an external component. In this blog post we’ll see how to change the validation trigger default behavior. We’ll cover the unobtrusive javascript with Jquery validation with Asp.net mvc application.

Problem – The validation doesn’t trigger while user is entering data in the input field. Default behavior shows errors either on ‘onfocusout’ or when submitting the form.

Solution – Write a custom handler for ‘onkeyup’ event, attach it with JQuery validator and trigger the unobtrusive js event for form invalidation.

Here’s the complete code snippet that will do the trick for you by enabling the ‘onkeyup’ event:
Explanation - 
1. Get the validator object.
var $validatr = $('form').data('validator');

2. Adding a new event handler for ‘onkeyup’ event of Validator object. The handler takes two argument the source element and the event occurred. Validate the element, if it’s invalid trigger the unobtrusive form validation event, which would build up the validation errors summary.
var settngs = $validatr.settings;
 
settngs.onkeyup = function (element, eventType) {     
if (!$validatr.element(element)) {        
$(this.currentForm).triggerHandler("invalid-form", [this]);    
}
}
3. Disable any other events if you like.
settngs.onfocusout = false;

Here’s the result:

No comments:

Post a Comment