May 14, 2008

asp:RequiredFieldValidator (or any asp validator perhaps?) control with image instead asterix

I was wondering how can I create required field validator with image, instead this ugly asterix, used in most forms.

The answer was pretty obvious but I couldn't see it for quite a long time. I even decided to write my own validator to inherit from RequiredFieldValidator and hopefully overwite the HtmlTextWriter thing in order to achieve this functionality.

The solution is pretty strightforward, you don't need new controls, you don't need anything, all you need is :



<asp:TextBox ID="txtFakeTextBox" runat="server">asp:TextBox>

<asp:RequiredFieldValidator ID="rfFake" runat="server" ControlToValidate="txtFakeTextBox" Display="Dynamic" EnableClientScript="true">
/><asp:Image ID="imgTest" runat="server" ImageUrl="~/images/error.png"/>

asp:RequiredFieldValidator>

<br />

<asp:Button ID="btnOpenFakeValidator" runat="server" Text="Validate!" CausesValidation="true" />





What you do is to place and control between the opening and closing tags of the asp:RequiredFieldValidator. Pretty easy, huh?




3 comments:

Veselin Kolev said...

Hi Pavel! Great topic!
I just want to add - the more interesting question in my opinion is how to add this pictures on existing application without putting code for every validator? One possible solution can be using control adapter for all validators. This will change the look of every existing application just with a few lines of code. However there can be little performance overhead but this will not be a problem compared to the power which can be given to you.
I will try to post a sample soon showing this one.

lizzarde said...

Hi from me too:) As Vesko said in previous comment (and with his help;) here is the sample code for control adapter that can overtake all validators in existing application. It simply changes the span tag and inserts the image in it:

// Adapter
public class rfvControlAdapter : ControlAdapter
{
protected override void Render(HtmlTextWriter writer)
{
StringWriter stringWriter = new StringWriter();
HtmlTextWriter htmlTextWriter = new HtmlTextWriter(stringWriter);
base.Render(htmlTextWriter);
string htmlString = stringWriter.ToString();
htmlString = htmlString.Replace(">*</span>", "><img src=\"images\\error.gif\" /></span>");
writer.Write(htmlString);
}
}

Павелъ Дончевъ said...

Hi, guys! Thanks for your attention and thanks for your efforts!

@Georgi(lizzarde) - great job!
@Vesko - great idea.

I found something, however, I consider more elegant and I made another post on the topic. The idea is not to touch the code but to use mix of App_Theme + web.config declarations in order to make all validators across the project with images instead asterix.

I think this approach is better if you want to have some validators with images, some with some other images, some with links and some with asterix ;).

Here is the link to the new post.


Once again - THANKS FOR YOUR EFFORTS!