Apply the same CSS class to all validators in a web project

I recently had to add a CSS class to all validators in an ASP.NET web application.I started with the theme’s skin file:

<asp:CompareValidatorrunat="server"CssClass="error"/><asp:CustomValidatorrunat="server"CssClass="error"/><asp:RequiredFieldValidatorrunat="server"CssClass="error"/><belCommon:ZipCodeValidatorrunat="server"CssClass="error"/><belCommon:PhoneNumberValidatorrunat="server"CssClass="error"/>

But what if I decide to use another validator down the road? I would have to remember to add it to the skin. Knowing that I was bound to forget, I sought out another method. After doing some digging, I found that ASP.NET generates a JavaScript variable called Page_Validators. This is an array of all the validator span elements on the current page. Now that I have access to the spans, I could write a script in the site’s Master Page to apply the class:

if (PageValidators != null) { for (i = 0; i < PageValidators.length; i++) { Page_Validators[i].className = "error"; } }

To have it run when the page is loaded, I added it as an Sys.Application.init handler:

Sys.Application.addinit(function(sender, args) { if (PageValidators != null) { for (i = 0; i < PageValidators.length; i++) { PageValidators[i].className = "error"; } } });

You could also use jQuery’s document.ready handler:

$(document).ready(function() { if (PageValidators != null) { for (i = 0; i < PageValidators.length; i++) { Page_Validators[i].className = "error"; } } });

John Rummell

Read more posts by this author.