0

This is my issue: We use custom validators for some fields. And now we want to change validation markup. For now this is something like that: <span id="CreateProfile_EmailValidator">Email is in Incorrect Format</span>.

Can I somehow change this markup? For example add some <div> elements?

UPD: I looked not for onetime workaround. (Please see discussion of the MikeSmithDev's answer)

2
  • What do you mean exactly? You can apply a class (CssClass) to the validator. Also, RegularExpressionValidator is good for email. Commented Mar 13, 2013 at 13:08
  • @MikeSmithDev I now about CssClass, but I need instead <span> use div and other html elements. Commented Mar 13, 2013 at 13:09

2 Answers 2

3

You can inherit from BaseValidator or CustomValidator class and override Render method, and then generate whatever markup you want.

public class MyCustomValidator : CustomValidator
{
    protected override void Render(HtmlTextWriter writer)
    {
        writer.RenderBeginTag("div");
        base.Render(writer);
        writer.RenderEndTag();
    }
}
Sign up to request clarification or add additional context in comments.

Comments

2

Use WebControlAdapter to change the way of how CustomValidator is rendered. You will want to override RenderBeginTag and RenderEndTag methods to render your div around the default span.

public class CustomValidatorAdapter : WebControlAdapter
{
    protected override void RenderBeginTag(HtmlTextWriter writer)
    {
        writer.RenderBeginTag("div");
                base.RenderBeginTag(writer);
    }

    protected override void RenderEndTag(HtmlTextWriter writer)
    {
                base.RenderEndTag(writer);
        writer.RenderEndTag(); // this will close div
    }
}

To connect this adapter to you application you have two options. First is to do it programmatically in page constructor:

var adapters = Context.Request.Browser.Adapters;
var customValidatorType = typeof(CustomValidator).AssemblyQualifiedName;
var adapterType = typeof(CustomValidatorAdapter).AssemblyQualifiedName;
if (!adapters.Contains(customValidatorType))
{
    adapters.Add(customValidatorType, adapterType);
}

Second option is to use .browser file:

Add new Browser File to your project. It will reside in App_Browsers folder. Then replace contents with following declaration:

<browsers>
    <browser refID="Default">
            <controlAdapters>
                <adapter controlType="System.Web.UI.WebControls.CustomValidator" 
                         adapterType="<your namespace>.CustomValidatorAdapter" />
            </controlAdapters>
    </browser>
</browsers>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.