This technique is very useful. If we have multiple controls, we only use one verification control to verify them. This reduces the page size and improves performance, because each verification control is rendered as a span on the client. If a page contains hundreds of controls, the page will be very bloated.
In this articleArticleIn the demo, several textbox dynamically created, I only use one verification control to verify them.
1. On the 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. on the server side, associate the verification control with the onfocus event of textbox:
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 }
4. The client verification function is as follows:
1 Function Validatetextbox (sender, argS)
2 {
3 If (ARGs. Value = "" )
4 {
5 Sender. errormessage = " <B> this field cannot be blank. " ;
6 Sender. innerhtml = " <B> this field cannot be blank. " ;
7 Args. isvalid = False ;
8 Return ;
9 }
10 If (Isnan (ARGs. Value ))
11 {
12 Sender. errormessage = " <B> this field can only be a number. " ;
13 Sender. innerhtml = " <B> this field can only be a number. " ;
14 Args. isvalid = False ;
15 Return ;
16 }
17 If (Number (ARGs. value) < 100 ){
18 Sender. errormessage = " <B> the value of this field cannot be less than 100. </B> " ;
19 Sender. innerhtml = " <B> the value of this field cannot be less than 100. </B> " ;
20 Args. isvalid = False ;
21 Return ;
22 }
23 }
In fact, it mainly uses the validatorhookupcontrol (curobj, validationcontrol) function.
Enter 1 in the First Textbox, and the prompt is: the value of this field cannot be less than 100.
Enter a in the second Textbox, and the prompt is: this field can only be a number.
Enter a value in the third textbox and delete it after the focus is lost. The prompt is: this field cannot be blank ..
The onfocus event can be changed to your corresponding event, and the validatetextbox function can also be expanded.
Code:/files/zhuqil/website1.zip