If you are like me, you hate having to create the required field validators for a bunch of TextBox controls. Even more if you are adding Ajax ValidatorCallout controls to all of them. Sure, you could create another server control to extent the Textbox to automatically include this…but here is a simple alternative.
I created a method that cycles through all of the controls and checks to see if it has the attribute “Required”, and if so, then add the RequiredFieldValidator and Ajax callout controls automatically. You could obviously expand on this to meet your specific needs.
Here is how you would markup your TextBox control:
<asp:TextBox Required=”true” ValidationGroup=”valGroup” ID=”TextBox1″ runat=”server” />
Here is the method in the code behind:
private void AddRequiredValidations(ControlCollection controls)
{
List requiredValidators = new List();
for (int i = 0; i < controls.Count; i++)
{
if (controls[i] is TextBox)
{
TextBox tb = (TextBox)controls[i];
if (tb.Attributes["Required"] != null && Convert.ToBoolean(tb.Attributes["Required"]))
{
RequiredFieldValidator requiredValidator = new RequiredFieldValidator();
requiredValidator.ErrorMessage = "Required";
requiredValidator.ID = "required" + tb.ID;
requiredValidator.Display = ValidatorDisplay.None;
requiredValidator.ValidationGroup = tb.ValidationGroup;
requiredValidator.ControlToValidate = tb.ID;
// Add the RequiredFieldValidator to a list to be added later
// Since we can't add them to the control as we are cycling through them
requiredValidators.Add(requiredValidator);
tb.CausesValidation = true;
}
}
if (controls[i].HasControls()) // If this control has child controls
{
AddRequiredValidations(controls[i].Controls); // Search the child controls too
}
}
// Now we can actually add the RequiredFieldValidators since we are done cycling through the existing controls
for (int i = 0; i < requiredValidators.Count; i++)
{
AjaxControlToolkit.ValidatorCalloutExtender callout = new AjaxControlToolkit.ValidatorCalloutExtender();
callout.TargetControlID = requiredValidators[i].ID;
callout.ID = requiredValidators[i].ID + "Callout";
controls.Add(requiredValidators[i]);
controls.Add(callout);
}
}
Then all you have to do is call it in your Page_Load() method:
AddRequiredValidations(this.Controls);
This will work not only for a singe TextBox control, but also for TextBox controls buried inside a GridView or Repeater!





#1 by Fred on January 23, 2012 - 5:20 am
what is the type of
List requiredValidators = new List() ???
#2 by Eric on January 23, 2012 - 8:32 am
A generic list would have been better and more descriptive, but to answer your question, it should be a list of type RequiredFieldValidator. You will then see at line 38 we spin back through the list and add each newly created RequiredFieldValidator to the Page’s control collection.
This would be a better type-safe declaration:
var requiredValidators = new System.Collections.Generic.List<System.Web.UI.WebControls.RequiredFieldValidator>();