May 16, 2008

Changing asp:RequiredFieldValidator (why not any validator) in existing projects relatively easy

The last post I posted was about changing the asterix of asp:RequiredFieldValidator (I don’t see a reason this not to work for any validator). My friends Georgi and Vesko noticed that I am not thinking about how can we apply such a change in a big project.
They also provided me with a solution to this problem. The solution is pretty good; it uses the control adapters approach to change the span which is rendered as output.

But I found another way, I consider more elegant. Instead using the control adapter approach, you can simply repeat the following steps:

1. Right click on your project and choose Add -> ASP.NET Folder -> Theme
2. Name your theme folder “Default” for example.
3. Right click your theme folder and choose Add -> New Item

4. From the Add New Item dialog choose “Skin File”, name it “Default.Skin” and clik OK
5. Open “Default.Skin” file and add the following code


<asp:RequiredFieldValidator runat="server">
   <img src="~/images/validator.png" width="15" height="15"/>
asp:RequiredFieldValidator>

This will register the default behavior for asp:RequiredFieldValidator controls on your site.

6. Add the above code for all validators you want to affect.
7. Open your web.config file and find the section
8. Register the theme you just created like this :

<pages theme="Default">

So it can propagate throughout all of your pages.

Add as much as validators you want on ANY page of your site. The web.config declaration should take care to apply your generic skin to all validators on your pages.

Please note - if you have explicitly defined Theme for a page - the web.config declaration will be overridden, in such case - you may want to move you control declarations from the skin in the Default theme to a skin in the theme which is set for a page you want this changes to take effect.

Good Luck!

No comments: