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 the 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.

register

Here’s the complete code snippet that will do the trick for you by enabling the ‘onkeyup’ event:

  1. $(document).ready(function()  
  2.  {  
  3.     var $validatr = $('form').data('validator');  
  4.     varsettngs = $validatr.settings;  
  5.   
  6.   
  7.     settngs.onkeyup = function(element, eventType)  
  8.     {  
  9.         if (!$validatr.element(element))  
  10.         {  
  11.             $(this.currentForm).triggerHandler("invalid-form", [this]);  
  12.         }  
  13.     };  
  14.   
  15.   
  16.     settngs.onfocusout = false;  
  17. });  
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 arguments; the source element and the event occurred. Validate the element, if it’s invalid trigger the unobtrusive form validation event, which will build up the validation errors summary.
    1. varsettngs = $validatr.settings;  
    2.   
    3. settngs.onkeyup = function(element, eventType)  
    4. {  
    5.     if (!$validatr.element(element))  
    6.     {  
    7.         $(this.currentForm).triggerHandler("invalid-form", [this]);  
    8.     }  
    9. }  

  3. Disable any other events if you like.

    settngs.onfocusout = false;

Here’s the result:

result

X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now