This technique is very useful. If we have multiple controls, we validate it with only one validation control. This reduces page size and improves performance because each validation control is rendered as span on the client, and if a page contains hundreds of controls, it can make the page very bulky.
In the demo of this article, a few of the dynamically created textbox, I use only one validation control to validate them.
1. ASPX page:
1 <body>
2 <form id="form1" runat="server">
3 <div>
4 <asp:CustomValidator ID="CustomValidator1" runat="server" ></asp:CustomValidator>
5 <asp:ValidationSummary ID="ValidationSummary1" runat="server" />
6 </div>
7
8 </form>
9 </body>
2. To associate the validation control with the onfocus event of the textbox on the server side:
1 protected void Page_Load(object sender, EventArgs e)
2 {
3 if (!IsPostBack)
4 {
5 for (int i = 0; i < 10; i++)
6 {
7 TextBox tb = new TextBox();
8 tb.ID = "tb" + i.ToString();
9 tb.Attributes.Add ("onfocus", "HookUpControl(this,'" + CustomValidator1.ClientID + "')");
10 Page.Form.Controls.Add(tb);
11 }
12 }
13 }
3. The Hookupcontrol function is as follows:
1 function HookUpControl(curObj, validatorClientID)
2 {
3 var validationControl = document.getElementById (validatorClientID);
4 validationControl.controltovalidate = curObj.id;
5 validationControl.clientvalidationfunction = "validatetextbox";
6 validationControl.validateemptytext = "true";
7 ValidatorHookupControl(curObj, validationControl);
8 }