Dynamically Inject Validation Controls From A Base ASP.NET Page

I've been out of work this week sick (which really sucks...I don't do very well with idle time, plus I haven't been sick enough to miss work in many years), so what better time to catch up on some blogging.

We had an interesting scenario at work recently whereby we needed to dynamically attach a number of asp.net validation controls to various TextBox controls on all of our existing pages. Specifically we had written a custom validation control which would test a control to make sure it didn't contain any HTML tags (a common enough scenario). This post assumes knowledge of authoring custom asp.net validation controls, i.e. inherit from BaseValidator and override EvaluateIsValid. For anyone needing a refresher, check out this MSDN post on custom validation controls.

There are multiple ways to go about attaching asp.net validation controls to the controls they need to validate, but in the end I settled on going with a base page class that our existing base page could inherit from...you just plug in the base page and everything is automagically wired up during the page request cycle. Given that asp.net validation controls will almost always need to validate TextBox controls (more specifically, any type of control that accepts user input), all we need to do is find controls that implement the IEditableTextControl interface. Existence of this interface in the controls inheritance hierarchy means that the control supports user editing of text.

So in short, here is the plan of attack:

  • Author our custom validation control, or utilize one of the built in asp.net validation controls.
  • Create a base page that loops through all of the contained controls, and when a control is found that implements the IEditableTextControl interface, instantiate and attach our validation control. Recursion seems to be the best way to go about this.
  • [optional] Inject a ValidationSummary on the parent page to notify the user of any failed validation attempts.

Here is the code for a base page that dynamically attaches a custom validation control called HtmlInputValidator:

public class HtmlValidationBasePage : Page
    protected HtmlValidationBasePage()
    protected override void OnLoad(EventArgs e)
        List<Control> controls = new List<Control>();
        FindControls<Control>(this.Page.Controls, controls);
        if (controls.Count > 0)
            controls.ForEach(delegate(Control control)
                IEditableTextControl textControl = control as IEditableTextControl;
                if (textControl != null)
                    HtmlInputValidator handler = new HtmlInputValidator();
                    handler.ControlToValidate = control.UniqueID;
                    handler.Display = ValidatorDisplay.Dynamic;
                    handler.Text = "Failed Validation for control " + control.ID;
                    handler.ErrorMessage = "Failed Validation for control " + control.ID;
                    handler.SetFocusOnError = true;
                    handler.EnableClientScript = false;
                    handler.ID = control.ID + "Validator";
        ValidationSummary summary = new ValidationSummary();
        summary.ShowSummary = true;
        summary.DisplayMode = ValidationSummaryDisplayMode.List;
    // Recurse through all of the controls on the page
    protected T FindControls<T>(ControlCollection controls, List<T> foundControls) where T : Control
        T found = default(T);
        if (controls != null && controls.Count > 0)
            for (int i = 0; i < controls.Count; i++)
                found = controls[i] as T;
                if (found != null)
                found = FindControls<T>(controls[i].Controls, foundControls);
        return found;

Of course this base page could (and should) be further extended to support turning validation on/off, or only validating certain groups of controls...the above sample is simply for sake of brevity and should serve as a starting point only.

I've always been a huge proponent of authoring a custom base asp.net page class from which the rest of your pages will inherit...it is without a doubt the easiest (and cheapest) way for you to get reusable functionality distributed to all of your asp.net pages with minimal coding effort. Their power really starts to shine in scenarios such as the one outlined in this post.

See attached file below


# DotNetKicks.com said:

You've been kicked (a good thing) - Trackback from DotNetKicks.com

Wednesday, September 26, 2007 11:33 AM
# 10 Hot ASP.NET Tips and Tricks - 10/28/2007 said:

Pingback from  10 Hot ASP.NET Tips and Tricks - 10/28/2007

Friday, September 28, 2007 2:59 AM
# Andre said:

Hi there im trying to convert the above algorythm to vb but having big problems

can anyone help ?

Tuesday, July 1, 2008 7:44 AM
# w3cvalidation said:

Nice information, I really appreciate the way you presented.Thanks for sharing..

Friday, April 9, 2010 12:14 AM