views:

658

answers:

3

I want all of the validators in an ASP.Net 3.5 website to have a CssClass value of "error". My initial thought was to do this in a theme skin like so:

<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" />

This is only a partial listing of validators that I use. Ideally, I would like to do something like this:

<asp:BaseValidator runat="server" 
    CssClass="error" />

And because all validators inherit from BaseValidator, I would expect that this would work, but it doesn't. Is there a way to accomplish this without adding every single validator control to the skin explicitly?

Update:

I found a different approach using javascript:

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

ASP.Net generates a javascript variable called Page_Validators, which is an array of the validation spans. This script checks to see if it exists and then loops through and sets the class name. I added this to the master page and its working so far.

+2  A: 

Not that I am aware of, when defining a skin you are specifically working with individual controls and you don't have a way of specifying it any other way, as it matches based on the tags used.

From the looks of it though, you are creating your own custom validators as well, you might modify your controls to have a default cssclass of error to save a bit of time.

Mitchel Sellers
I was afraid of that, thanks!
jrummell
+1  A: 

I'd be tempted to iterate over the controls of the page in the server pageload method and to apply the css class there:

foreach (object obj in this.Controls)
{
  if (obj is BaseValidator)
  {
     ((BaseValidator)obj).CssClass = "error";
  }
}

This may not be the best way to do this and I've not had the opportunity to test it but hopefully it might help you along the way.

Lazarus
I just arrived at a similar solution, but in client side code. Thanks!
jrummell
+1  A: 

I found a different approach using javascript:

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

ASP.Net generates a javascript variable called Page_Validators, which is an array of the validation spans. This script checks to see if it exists and then loops through and sets the class name. I added this to the master page and its working so far.

jrummell