Thursday, December 23, 2010

Hooking into ASP Client Side Validation

The Problem: The ASP Validators are hard to style. The Validators only render a <span> with the error information. What if you want to display the complete div around the control to be red when an error occures? This is likely not possible with the standard asp validators.

What you can do is o write a decorator in javascript. The function which displays the errormessages is the "ValidatorUpdateDisplay" method.


1:  /**  
2:   * @requires JQuery 1.4.x  
3:   */  
4:  var Biggy = {};  
5:    
6:  Biggy.Validator = {  
7:   /**  
8:   * Decorator for the ms validator update function  
9:   *  
10:   * @param {orig_fn} Function  
11:   * The function to decorate  
12:   * @return Function  
13:   * The decorated fucntion  
14:   */  
15:   UpdateDisplayDecorator : function(orig_fn) {  
16:    return function(){  
17:   var originalfunc = orig_fn.apply(this, arguments);  
18:   Biggy.Validator.UpdateParentDisplay( arguments[0] );  
19:   return originalfunc;  
20:    };  
21:   },  
22:    
23:   /**  
24:   * This method is used to update the class of parent dom elements  
25:   * when the validator function raised an error  
26:   *  
27:   * @param {val} Object  
28:   * The DOM <span> object created by the validator  
29:   */  
30:   UpdateParentDisplay : function( val ) {   
31:   if (!val.isvalid){  
32:    $(val).css("visibility", "visible").show().parent().show();  
33:   }else{  
34:    $(val).css("visibility", "hidden").hide().parent().hide();  
35:   }  
36:     
37:   }  
38:  }  
39:    
40:  // Create decorated function  
41:  ValidatorUpdateDisplay = Biggy.Validator.UpdateDisplayDecorator(ValidatorUpdateDisplay);  

Now every time a validator shows a error message the "UpdateParentDisplay" function will also be called. Within this function you get the dom object of the validator as parameter and can now do anything you want.