实现一个自定义验证器控件

       今天由于项目需要在页面上实现一个复合验证功能,本来想用脚本实现,发现会写一大堆重复的隐藏代码.最后选择了自己实现一个自定义验证器控件.这样以后也可以直接拿来复用. 因为往往需要同时满足1:用户输入不能为空.2: 输入值必须满足相应的格式. 这样的功能.而不用再为数据库添加字段来完成.

代码如下:
  1using System;
  2using System.ComponentModel;
  3using System.Drawing;
  4using System.Security.Permissions;
  5using System.Web;
  6using System.Web.UI;
  7using System.Web.UI.WebControls;
  8
  9namespace Kim.AspNet.Validatator.Controls
 10{
 11    [
 12    AspNetHostingPermission(SecurityAction.Demand,
 13        Level = AspNetHostingPermissionLevel.Minimal),
 14    AspNetHostingPermission(SecurityAction.InheritanceDemand,
 15        Level = AspNetHostingPermissionLevel.Minimal),
 16    DefaultEvent("ValidTextBoxChanged"),
 17    DefaultProperty("Text"),
 18    ToolboxData("<{0}:ValidTextBox runat=\"server\"> </{0}:ValidTextBox>"),
 19    ]
 20    public class ValidTextBox : CompositeControl
 21    {
 22        //Contact Ways 
 23        private DropDownList validType;
 24        //User Enter Values
 25        private TextBox validTextBox;
 26    
 27        //valid user enter values
 28        //can not empty
 29        private RequiredFieldValidator emailValidator;
 30        private RequiredFieldValidator handphoneValidator;
 31        private RequiredFieldValidator phoneValidator;
 32
 33        //have the right format
 34        private RegularExpressionValidator emilFormatValidator;
 35        private RegularExpressionValidator handphoneFormatValidator;
 36        private RegularExpressionValidator phoneFormatValidator;
 37
 38        private static readonly object EventValidKey =
 39            new object();
 40       
 41        // get TextBox value
 42       [
 43       Bindable(true),
 44       Category("Appearance"),
 45       DefaultValue(""),
 46       Description("get value from textbox")
 47       ]
 48        public string TextValue
 49        {
 50            get
 51            {
 52                EnsureChildControls();
 53                return validTextBox.Text;
 54            }

 55            set
 56            {
 57                EnsureChildControls();
 58                validTextBox.Text = value;
 59                
 60            }

 61        }

 62
 63
 64        [
 65        Bindable(true),
 66        Category("Appearance"),
 67        DefaultValue(""),
 68        Description("Error message for the phone validator.")
 69        ]
 70        public string ValidPhoneErrorMessage
 71        {
 72            get
 73            {
 74                EnsureChildControls();
 75                return phoneValidator.ErrorMessage;
 76            }

 77            set
 78            {
 79                EnsureChildControls();
 80                phoneValidator.ErrorMessage = value;
 81                phoneValidator.ToolTip = value;
 82            }

 83        }

 84
 85
 86        [
 87        Bindable(true),
 88        Category("Appearance"),
 89        DefaultValue(""),
 90        Description("Error message for the hand phone validator.")
 91        ]
 92        public string ValidHandPhoneErrorMessage
 93        {
 94            get
 95            {
 96                EnsureChildControls();
 97                return handphoneValidator.ErrorMessage;
 98            }

 99            set
100            {
101                EnsureChildControls();
102                handphoneValidator.ErrorMessage = value;
103                handphoneValidator.ToolTip = value;
104            }

105        }

106
107       
108        [
109        Bindable(true),
110        Category("Appearance"),
111        DefaultValue(""),
112        Description("Error message for the e-mail validator.")
113        ]
114        public string ValidEmailErrorMessage
115        {
116            get
117            {
118                EnsureChildControls();
119                return emailValidator.ErrorMessage;
120            }

121            set
122            {
123                EnsureChildControls();
124                emailValidator.ErrorMessage = value;
125                emailValidator.ToolTip = value;
126            }

127        }

128     
129
130        // The Valid event.
131        [
132        Category("Action"),
133        Description("Raised when the user input the value.")
134        ]
135        public event EventHandler ValidTextBoxChanged
136        {
137            add
138            {
139                Events.AddHandler(EventValidKey, value);
140            }

141            remove
142            {
143                Events.RemoveHandler(EventValidKey, value);
144            }

145        }

146
147
148        protected virtual void OnValidTextBoxChanged(EventArgs e)
149        {
150            EventHandler TextBoxChangedHandler =
151                (EventHandler)Events[EventValidKey];
152            if (TextBoxChangedHandler != null)
153            {
154                TextBoxChangedHandler(this, e);
155            }

156        }

157       
158 
159        private void _TextBox_Changed(object source, EventArgs e)
160        {
161            OnValidTextBoxChanged(EventArgs.Empty);
162        }

163
164        protected override void RecreateChildControls()
165        {
166            EnsureChildControls();
167        }

168
169
170        protected override void CreateChildControls()
171        {
172            Controls.Clear();
173
174            ListItem list;
175            validType = new DropDownList();
176            validType.ID = "validDrpList";        
177
178            list = new ListItem();
179            list.Text = "电话";
180            list.Value = "0";
181            validType.Items.Add(list);
182           
183            list = new ListItem();
184            list.Text = "邮件";
185            list.Value = "1";
186            validType.Items.Add(list);
187
188            list = new ListItem();
189            list.Text = "手机";
190            list.Value = "2";
191            validType.Items.Add(list);
192
193            validTextBox = new TextBox();
194            validTextBox.ID = "validTextBox";
195
196            //phone valid
197            phoneValidator = new RequiredFieldValidator();
198            phoneValidator.ID = "phoneValidator";
199            phoneValidator.ControlToValidate = validTextBox.ID;
200            phoneValidator.Text = "电话号码不能为空!";
201            phoneValidator.Display = ValidatorDisplay.Dynamic;
202
203            phoneFormatValidator = new RegularExpressionValidator();
204            phoneFormatValidator.ID = "phoneFormatValidation";
205            phoneFormatValidator.Text = "电话号码格式不正确";
206            phoneFormatValidator.Display = ValidatorDisplay.Dynamic;
207            phoneFormatValidator.ControlToValidate = validTextBox.ID;
208            phoneFormatValidator.ValidationExpression = @"(0\d{2}-\d{8}|0\d{3}-\d{7})-\d{2,4}|(0\d{2}-\d{8}|0\d{3}-\d{7})"
209        
210            //email valid
211            emailValidator = new RequiredFieldValidator();
212            emailValidator.ID = "emailValidator";
213            emailValidator.ControlToValidate =
214                validTextBox.ID;
215            emailValidator.Text = "请输入邮件地址!";
216            emailValidator.Display = ValidatorDisplay.Dynamic;
217
218            emilFormatValidator = new RegularExpressionValidator();
219            emilFormatValidator.ID = "emailFormatValidation";
220            emilFormatValidator.Text = "邮件格式不正确";
221            emilFormatValidator.Display = ValidatorDisplay.Dynamic;
222            emilFormatValidator.ControlToValidate = validTextBox.ID;
223            emilFormatValidator.ValidationExpression=@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*";
224
225            //handphone valid
226            handphoneValidator = new RequiredFieldValidator();
227            handphoneValidator.ID = "handphoneValidator";
228            handphoneValidator.ControlToValidate =
229                validTextBox.ID;
230            handphoneValidator.Text = "请输入手机号码!";
231            handphoneValidator.Display = ValidatorDisplay.Dynamic;
232
233            handphoneFormatValidator = new RegularExpressionValidator();
234            handphoneFormatValidator.ID = "handphoneValidation";
235            handphoneFormatValidator.Text = "手机号码格式不正确";
236            handphoneFormatValidator.Display = ValidatorDisplay.Dynamic;
237            handphoneFormatValidator.ControlToValidate = validTextBox.ID;
238            handphoneFormatValidator.ValidationExpression = @"^1[3,5][0-9][0-9]{8}$"
239 
240            validTextBox.TextChanged += new EventHandler(_TextBox_Changed);
241            validType.AutoPostBack = true;
242
243            this.Controls.Add(validType);
244            this.Controls.Add(validTextBox);
245
246            this.Controls.Add(phoneValidator);
247            this.Controls.Add(phoneFormatValidator);
248
249            this.Controls.Add(emailValidator);
250            this.Controls.Add(emilFormatValidator);
251
252            this.Controls.Add(handphoneValidator);
253            this.Controls.Add(handphoneFormatValidator);
254        }

255
256        protected override void Render(HtmlTextWriter writer)
257        {
258            AddAttributesToRender(writer);
259            writer.AddAttribute(
260                HtmlTextWriterAttribute.Cellpadding,
261                "1"false);
262            writer.RenderBeginTag(HtmlTextWriterTag.Table);
263
264            //phone valid
265            if (validType.SelectedIndex == 0)
266            {
267                writer.RenderBeginTag(HtmlTextWriterTag.Tr);
268
269                writer.RenderBeginTag(HtmlTextWriterTag.Td);
270                validType.RenderControl(writer);
271                writer.RenderEndTag();
272
273                writer.RenderBeginTag(HtmlTextWriterTag.Td);
274                validTextBox.RenderControl(writer);
275                writer.RenderEndTag();
276
277                writer.RenderBeginTag(HtmlTextWriterTag.Td);
278                phoneValidator.RenderControl(writer);
279                writer.RenderEndTag();
280
281                writer.RenderBeginTag(HtmlTextWriterTag.Td);
282                handphoneFormatValidator.RenderControl(writer);
283                writer.RenderEndTag();
284
285                writer.RenderEndTag();
286            }

287            //email valid
288            if (validType.SelectedIndex == 1)
289            {
290                writer.RenderBeginTag(HtmlTextWriterTag.Tr);
291                writer.RenderBeginTag(HtmlTextWriterTag.Td);
292                validType.RenderControl(writer);
293                writer.RenderEndTag();
294
295                writer.RenderBeginTag(HtmlTextWriterTag.Td);
296                validTextBox.RenderControl(writer);
297                writer.RenderEndTag();
298
299                writer.RenderBeginTag(HtmlTextWriterTag.Td);
300                emailValidator.RenderControl(writer);
301                writer.RenderEndTag();
302
303                writer.RenderBeginTag(HtmlTextWriterTag.Td);
304                emilFormatValidator.RenderControl(writer);
305                writer.RenderEndTag();
306
307                writer.RenderEndTag();
308            }

309            //hand phone valid
310            if (validType.SelectedIndex == 2)
311            {
312                writer.RenderBeginTag(HtmlTextWriterTag.Tr);
313                writer.RenderBeginTag(HtmlTextWriterTag.Td);
314                validType.RenderControl(writer);
315                writer.RenderEndTag();
316
317                writer.RenderBeginTag(HtmlTextWriterTag.Td);
318                validTextBox.RenderControl(writer);
319                writer.RenderEndTag();
320
321                writer.RenderBeginTag(HtmlTextWriterTag.Td);
322                handphoneValidator.RenderControl(writer);
323                writer.RenderEndTag();
324
325                writer.RenderBeginTag(HtmlTextWriterTag.Td);
326                phoneFormatValidator.RenderControl(writer);
327                writer.RenderEndTag();
328                writer.RenderEndTag();
329            }
                    
330            writer.RenderEndTag();
331        }

332    }

333}

注意:开发环境为vs2008

posted on 2008-03-27 20:47  kim  阅读(2735)  评论(4编辑  收藏  举报

导航