by jrummell
16. August 2009 14:33
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:CompareValidator runat="server"
CssClass="error" />
<asp:CustomValidator runat="server"
CssClass="error" />
<asp:RequiredFieldValidator runat="server"
CssClass="error" />
<belCommon:ZipCodeValidator runat="server"
CssClass="error" />
<belCommon:PhoneNumberValidator runat="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 (Page_Validators != null)
{
for (i = 0; i < Page_Validators.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.add_init(function(sender, args)
{
if (Page_Validators != null)
{
for (i = 0; i < Page_Validators.length; i++)
{
Page_Validators[i].className = "error";
}
}
});
You could also use jQuery’s document.ready handler:
$(document).ready(function()
{
if (Page_Validators != null)
{
for (i = 0; i < Page_Validators.length; i++)
{
Page_Validators[i].className = "error";
}
}
});