free geoip Dynamically Inject Validation Controls From A Base ASP.NET Page - Jayson's Blog - jaysonKnight.com
jaysonKnight.com
A conduit to the voices inside my head.
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";
                    control.Controls.Add(handler);
                }
            });
        }
 
        ValidationSummary summary = new ValidationSummary();
        summary.ShowSummary = true;
        summary.DisplayMode = ValidationSummaryDisplayMode.List;
        Page.Form.Controls.Add(summary);
 
        base.OnLoad(e);
    }
 
    // 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)
                {
                    foundControls.Add(found);
                }
 
                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


Posted Wed, Sep 26 2007 1:28 PM by Jayson Knight
comments powered by Disqus

Comments

DotNetKicks.com wrote Dynamically Inject Validation Controls From A Base ASP.NET Page
on Wed, Sep 26 2007 11:33 AM

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

10 Hot ASP.NET Tips and Tricks - 10/28/2007 wrote 10 Hot ASP.NET Tips and Tricks - 10/28/2007
on Fri, Sep 28 2007 2:59 AM

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

Andre wrote re: Dynamically Inject Validation Controls From A Base ASP.NET Page
on Tue, Jul 1 2008 7:44 AM

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

can anyone help ?

w3cvalidation wrote re: Dynamically Inject Validation Controls From A Base ASP.NET Page
on Fri, Apr 9 2010 12:14 AM

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

Copyright © :: JaysonKnight.com
External Content © :: Respective Authors

Terms of Service/Privacy Policy