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

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";
        }
    }
});

Tags: ,

asp.net

Comments are closed

Powered by BlogEngine.NET 1.5.0.7
Theme by Mads Kristensen | Modified by Mooglegiant

About the author

John is a .Net Web Developer for a manufacturing company in Ohio. In his free time he enjoys web development, the outdoors, and spending time with his wife.

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in  anyway.

© Copyright 2009

Ads By Google