文档介绍:IT-Homer 专栏
成功是优点的发挥,失败是缺点的积累! 不为失败找理由,只为成功找
方法……
验证控件学习总结与正则表达式学习入门
2009-12-08 10:36 2884人阅读评论(1) 收藏举报
【】基础补习之验证控件
 
在做Web应用程序的时候,因为用户有可能输入各式各样的信息,经常需要大量的数据验证,如果交给服务器去验证
的话,无疑会增加服务器的压力,而且也容易造成程序的异常。甚至导致网站出现一些安全问题。因此我们在将这
些信息保存到网站的数据库之前,要对这些用户所输入的信息进行数据的合法性校验,以便后面的程序可以安全顺利
的执行。
提供了六种验证控件,可以实现以上功能。
<!--[if !supportLists]-->RequiredFieldValidator(必须字段验证)
<!--[if !supportLists]--><!--[endif]-->CompareValidator(比较验证)
<!--[if !supportLists]-->RangeValidator(范围验证)
<!--[if !supportLists]-->RegularExpressionValidator(正则表达式验证)
<!--[if !supportLists]--><!--[endif]-->CustomValidator(自定义验证)
<!--[if !supportLists]-->ValidationSummary(验证总结)
<!--[if !supportEmptyParas]--> <!--[endif]-->
验证控件基本成员:
ControlToValidate –要进行验证控件ID
ErrorMessage –验证失败时,出现的错误信息
IsValid –返回布尔值判断控件是否有效
Validate –验证控件的方法,同时改变IsValid属性
Display–错误信息的显示方式
None (控件的错误信息在页面中占有肯定位置)
Static (控件的错误信息出现时才占用页面控件.)
Dynamic (错误出现时不显示.)
 The RequiredFieldValidation Control
用于检查是否有输入值。用法如下:
       Required field: <asp:textbox id="textbox1" runat="server"/>
<asp:RequiredFieldValidator id="valRequired" runat="server" ControlToValidate="textbox1"
    ErrorMessage="* You must enter a value into textbox1" Display="dynamic">*
</asp:RequiredFieldValidator>
以上例子,实现当用户在textbox1中输入数据后,提交才会有效,否则激活验证控件显示错误信息。
<!--[if !supportEmptyParas]--> <!--[endif]-->
pareValidator Control
pareValidator可以用来验证注册时对密码的确认等。法如下:
Textbox 1: <asp:textbox id="textbox2" runat="server"/><br />
Textbox 2: <asp:textbox id="textbox3" runat="server"/><br />
<pareValidator id="pare" runat="server"
    ControlToValidate="textbox1" pare="textbox2"
    Operator="Equals"
1
Operator="Equals"
    ErrorMessage="* You must enter the same values into textbox 1 and textbox 2"
    Display="dynamic">*
</pareValidator>
上面例子验证textbox1和textbox2必须一致,两个控件根据 Operator属性进行比较。Operator属性可以设定为
Equal, GreterThan, pareValidator的另一个用法是和一个固定值比较:
<!--[if !supportEmptyParas]--> Field: <asp:textbox id="textb