验证控件
ASP.NET 2.0/3.5 一共提供了六个验证控件,在仔细了解了这几个验证控件后,才发现以前自己对验证控件有太多的误解,对其了解仅限于表象,对其应用也很不合理。以前我认为:
1. 验证控件和javascript的验证方式是一致的,都是通过js来进行验证
2. 验证控件太丑
3. 验证控件灵活度太差
效果和灵活度不如javascript的验证方式,这些控件最终还是会生成客户端的html和javascript,以上的这些都是对验证控件的误解。
在此章节开始之前,我先阐述并修正我对这些控件的误解。
1. 验证控件和javascript验证
验证控件通过服务器解释,最终呈现到浏览器,我们看到的仍然是一些html/css/js这些浏览器才能识别的语言,默认情况下它既在服务器端执行验证,也在客户端执行验证。服务端的验证是通过表单提交来实现,客户端的验证仍然是通过js来实现,这相当于执行了双重验证。但是js验证仅仅只是通过浏览器解释js脚本来进行验证。
2. 验证控件太丑
验证控件不是太丑,而是我不愿意为验证控件去写css,以前也一直认为验证控件就应该去写属性,但是写属性去调整一个控件,那代码就显得很臃肿,于是就产生了鄙视之的心理。
其实这是我先入为主的思想在作怪,我总是喜欢把客户端和服务器端的东西分开写,也许是Code Behind导致我精神分裂,喜欢把客户端和服务端的东西分的太清。
3. 验证控件灵活度差
验证控件在灵活度上确实不能和javascurip相比,它不能做出像javascript能够表现得动态效果,但是这并不代表它缺乏灵活度,如果足够了解这些控件,合理的结合使用其中的几种控件,也一样能够达到我们预期的效果(如果你正则表达式运用的比较好,只用RegularExpressionValidator控件就能完成所有验证)。
以上这些都是前话,现在开始正题,验证控件的讲述。
六个验证控件:
- RequireFieldValidator——用于要求用户在表单字段中输入必须的值。
- RangeValidator——用于检测一个值是否在确定的最小值和最大值之间。
- CompareValidator——用于比较一个值和另一个值或执行数据类型检查。
- RegularExpressValidator——用于比较一个值和正则表达式。
- CustomValidator——用于执行自定义验证。
- ValidationSummary——用于在页面中显示所有验证错误的摘要。
1.Page.IsValid属性,Display属性,Text属性
每一个验证控件都包含一个IsValid属性,验证正确则返回true,否则返回false。当页面中的所有验证控件的IsValid属性都为true时,Page.IsValid属性才返回true。
Display属性可接收的三个值:Static, Dynamic, None,Display的默认值是Static。
Text属性用于在验证失败时显示错误信息。
1: <%@ Page Language="C#"%>
2: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
3: <script runat="server">
4: void btnSubmit_Click(Object sender, EventArgs e)
5: {
6: //了解Page.IsValid属性
7: if (Page.IsValid)
8: {
9: lblResult.Text = @"<br />Product:" + this.txtProductName.Text +
10: @"<br />" + "Price:" + this.txtProductPrice.Text +
11: @"<br />" + "Quantity:" + this.txtProductQuantity.Text;
12: }
13:
14: }
15: </script>
16: <html xmlns="http://www.w3.org/1999/xhtml" >
17: <head id="Head1" runat="server">
18: <title>Order Form</title>
19: <style type="text/css">
20: body{
21: font-size: 1em;
22: font-family: "微软雅黑";
23: color: #333333;
24: }
25: </style>
26: </head>
27: <body>
28: <form id="form1" runat="server">
29: <div>
30:
31: <fieldset>
32: <legend>Product Order Form</legend>
33:
34: <asp:Label
35: ID="lblProductName"
36: runat="server"
37: Text="Product Name:"
38: AssociatedControlID="txtProductName"></asp:Label>
39: <asp:TextBox
40: ID="txtProductName"
41: runat="server"></asp:TextBox>
42: <!--Display属性-->
43: <asp:RequiredFieldValidator
44: ID="reqProductName"
45: runat="server"
46: Display="Static"
47: ControlToValidate="txtProductName"
48: Text="(Required)"></asp:RequiredFieldValidator>
49: <br /><br />
50:
51: <asp:Label
52: ID="lblProductPrice"
53: runat="server"
54: Text="Product Price:"
55: AssociatedControlID="txtProductPrice"></asp:Label>
56: <asp:TextBox
57: ID="txtProductPrice"
58: runat="server"></asp:TextBox>
59: <!--Display属性-->
60: <asp:RequiredFieldValidator
61: ID="reqProductPrice"
62: runat="server"
63: ControlToValidate="txtProductPrice"
64: Text="(Required)"
65: Display="Dynamic"></asp:RequiredFieldValidator>
66: <asp:CompareValidator
67: ID="cmpProductPrice"
68: runat="server"
69: ControlToValidate="txtProductPrice"
70: Text="(Invalid Price)"
71: Operator="DataTypeCheck"
72: Type="Currency"></asp:CompareValidator>
73: <br /><br />
74:
75: <asp:Label
76: ID="lblProductQuantity"
77: runat="server"
78: Text="Product Quantity:"
79: AssociatedControlID="txtProductQuantity"></asp:Label>
80: <asp:TextBox
81: ID="txtProductQuantity"
82: runat="server"></asp:TextBox>
83: <!--Display属性-->
84: <asp:RequiredFieldValidator
85: ID="reqProductQuantity"
86: ControlToValidate="txtProductQuantity"
87: Text="(Required)"
88: Display="Dynamic"
89: runat="server"></asp:RequiredFieldValidator>
90: <asp:CompareValidator
91: ID="cmpProductQuantity"
92: runat="server"
93: ControlToValidate="txtProductQuantity"
94: Text="(Invalud Quantity)"
95: Operator="DataTypeCheck"
96: Type="Currency"></asp:CompareValidator>
97: <br /><br />
98:
99: <asp:Button
100: ID="btnSubmit"
101: runat="Server"
102: Text="Submit"
103: OnClick="btnSubmit_Click" />
104:
105: </fieldset>
106:
107:
108: <asp:Label
109: ID="lblResult"
110: runat="server"></asp:Label>
111:
112: </div>
113:
114: </form>
115: </body>
116: </html>
当Display属性值为Static时,验证控件生成的代码如下:
1: <span id="reqProductName" style="color:Red; visibility:hidden">(Required)</span>
当Display属性值为Dynamic时,验证控件生成的代码则是:
1: <span id="reqProductPrice" style="color:Red; display:none">(Required)</span>
虽然visibility属性和display属性都会隐藏文本,但是visiblity即使隐藏了文本,仍然会占用空间,而display属性则不会。
通常情况下,我们都应该设置验证控件的Display属性为Dynamic,当有多个验证控件去验证某个控件时(比如TextBox控件),验证错误时的文本不会被推到右边。
Display属性为None时,验证控件中的Text将不显示,但我们仍然可以通过ValidationSummary控件来进行显示。
事实上,Text属性接收任何HTML字符串,比如Text=”<img src=’error.gif’ />”,以图片的形式来显示错误提示信息。
1: <%@ Page Language="C#"%>
2: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
3: <script runat="server">
4: </script>
5: <html xmlns="http://www.w3.org/1999/xhtml" >
6: <head id="Head1" runat="server">
7: <title>Validation Image</title>
8: </head>
9: <body>
10: <form id="form1" runat="server">
11: <div>
12: <asp:Label ID="FirstName" runat="server" Text="First Name:" AssociatedControlID="txtFirstName"></asp:Label>
13: <br />
14: <asp:TextBox ID="txtFirstName" runat="server"></asp:TextBox>
15:
16: <!--使用图片进行验证,Text字段接受任何HTML字符串-->
17: <asp:RequiredFieldValidator
18: ID="reqFirstName"
19: runat="server"
20: SetFocusOnError="true"
21: Text="<img src='error.png'/>"
22: ControlToValidate="txtFirstName"></asp:RequiredFieldValidator>
23: <br /><br />
24: <asp:Button ID="submit" runat="server" Text="Submit"/>
25: </div>
26: </form>
27: </body>
28: </html>
2.SetFocusOnError属性,Page.Validators属性
SetFocusOnError属性可以用于强调错误,所有的验证控件都支持这个属性。如果一个验证控件的SetFocusOnError属性为true,当与验证控件相关联的控件验证错误时,会自动关联到这个被验证控件,使它处于焦点状态。
用SetFocusOnError这个属性的强调效果并不明显,如果想真正强调验证错误的控件,可以用Page.Validators属性,这个属性表示页面的验证集合。我们可以利用Page.Validator属性来突出显示每一个验证错误的控件,代码如下:
1: <%@ Page Language="C#"%>
2: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
3: <script runat="server">
4: void Page_PreRender()
5: {
6: foreach (BaseValidator valControl in Page.Validators)
7: {
8: //通过Page.Validators属性找到验证控件
9: WebControl assControl = (WebControl)Page.FindControl(valControl.ControlToValidate);
10: if (!valControl.IsValid)
11: assControl.BackColor = System.Drawing.Color.Yellow;
12: else
13: assControl.BackColor = System.Drawing.Color.Gray;
14: }
15: }
16: </script>
17: <html xmlns="http://www.w3.org/1999/xhtml" >
18: <head id="Head1" runat="server">
19: <title>Show Page.Validators</title>
20: </head>
21: <body>
22: <form id="form1" runat="server">
23: <div>
24: <asp:Label
25: id="lblFirstName"
26: Text="First Name"
27: AssociatedControlID="txtFirstName"
28: Runat="server" />
29: <br />
30: <asp:TextBox
31: id="txtFirstName"
32: Runat="server" />
33: <!--只有当验证控件的EnableClientScript属性为false属性时,TextBox背景才会变色-->
34: <asp:RequiredFieldValidator
35: id="reqFirstName"
36: ControlToValidate="txtFirstName"
37: Text="(Required)"
38: EnableClientScript="false"
39: Runat="server" />
40:
41: <br /><br />
42:
43: <asp:Label ID="lblLastName" runat="server" Text="Last Name:"></asp:Label>
44: <br />
45: <asp:TextBox ID="txtLastName" runat="server"></asp:TextBox>
46: <asp:RequiredFieldValidator
47: ID="reqLastName"
48: runat="server"
49: ControlToValidate="txtLastName"
50: Text="(Required)"
51: EnableClientScript="false"></asp:RequiredFieldValidator>
52: <br /><br />
53:
54: <asp:Button
55: id="btnSubmit"
56: Text="Submit"
57: Runat="server" />
58:
59: </div>
60: </form>
61: </body>
62: </html>
3.使用验证组ValidationGroup
我们时常看到一些站点的注册表单和登陆表单在一个页面,而我们又需要对这两个表单进行验证。在验证控件中,有ValidationGroup这样一个属性,可以对验证控件进行分组,给那些验证登录的控件分一组,给用于注册的控件分一组,这样也只需要一个表单。
1: <%@ Page Language="C#"%>
2: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
3: <script runat="server">
4: /// <summary>
5: /// 登录
6: /// </summary>
7: /// <param name="sender"></param>
8: /// <param name="e"></param>
9: void btnLogin_Click(Object sender, EventArgs e)
10: {
11: if (Page.IsValid)
12: this.lblLoginResult.Text = "Log in Successful!";
13: }
14:
15: /// <summary>
16: /// 注册
17: /// </summary>
18: /// <param name="sender"></param>
19: /// <param name="e"></param>
20: void btnRegister_Click(Object sender, EventArgs e)
21: {
22: if (Page.IsValid)
23: this.lblRegisterResult.Text = "Registration Sucessful!";
24: }
25: </script>
26: <html xmlns="http://www.w3.org/1999/xhtml" >
27: <head id="Head1" runat="server">
28: <title>Show Validation Group</title>
29: <style type="text/css">
30: html
31: {
32: background-color: sliver;
33: font-family:Arial, Helvetica, sans-serif;
34: font-size: 12px;
35: color: #333;
36: }
37: .column
38: {
39: float: left;
40: width: 300px;
41: height: 300px;
42: margin-left: 100px;
43: background: white;
44: border: 1px solid #666;
45: padding: 10px;
46: }
47: input
48: {
49: border: 1px solid #ccc;
50: padding: 3px;
51: }
52: </style>
53: </head>
54: <body>
55: <form id="form1" runat="server">
56: <div class="column">
57: <fieldset>
58: <legend>Login</legend>
59: <p>Please log in to our Website.</p>
60: <asp:Label ID="lblUserName" runat="server" Text="User Name:" AssociatedControlID="txtUserName"></asp:Label>
61: <br />
62: <asp:TextBox ID="txtUserName" runat="server"></asp:TextBox>
63: <!--ValidationGroup="LoginGroup"-->
64: <asp:RequiredFieldValidator
65: ID="reqUserName"
66: runat="server"
67: ControlToValidate="txtUserName"
68: Text="(required)"
69: ValidationGroup="LoginGroup"></asp:RequiredFieldValidator>
70: <br /><br />
71:
72: <asp:Label ID="lblPassword" runat="server" Text="Password:" AssociatedControlID="txtPassword"></asp:Label>
73: <br />
74: <asp:TextBox ID="txtPassword" runat="server" ValidationGroup="LoginGroup"></asp:TextBox>
75: <!--ValidationGroup="LoginGroup"-->
76: <asp:RequiredFieldValidator
77: ID="reqPassword"
78: runat="server"
79: ControlToValidate="txtPassword"
80: Text="(required)"
81: ValidationGroup="LoginGroup"></asp:RequiredFieldValidator>
82: <br /><br />
83: <!--ValidationGroup="LoginGroup"-->
84: <asp:Button ID="btnLogin" runat="server" Text="Login" ValidationGroup="LoginGroup" OnClick="btnLogin_Click"/>
85: </fieldset>
86: <asp:Label ID="lblLoginResult" runat="server"></asp:Label>
87: </div>
88:
89: <div class="column">
90: <fieldset>
91: <legend>Register</legend>
92: <p>
93: If you do not have a User Name, please
94: register at our Website.
95: </p>
96: <asp:Label ID="lblFirstName" runat="server" Text="First Name:" AssociatedControlID="txtFirstName"></asp:Label>
97: <br />
98: <asp:TextBox ID="txtFirstName" runat="server"></asp:TextBox>
99: <!--ValidationGroup="RegisterGroup"-->
100: <asp:RequiredFieldValidator
101: ID="reqFirstName"
102: runat="server"
103: ErrorMessage="RequiredFieldValidator"
104: ControlToValidate="txtFirstName"
105: Text="(required)"
106: ValidationGroup="RegisterGroup"></asp:RequiredFieldValidator>
107: <br /><br />
108:
109: <asp:Label ID="lblLastName" runat="server" Text="Last Name:" AssociatedControlID="txtLastName"></asp:Label>
110: <br />
111: <asp:TextBox ID="txtLastName" runat="server"></asp:TextBox>
112: <!--ValidationGroup="RegisterGroup"-->
113: <asp:RequiredFieldValidator
114: ID="reqLastName"
115: runat="server"
116: ErrorMessage="RequiredFieldValidator"
117: ControlToValidate="txtLastName"
118: Text="(required)"
119: ValidationGroup="RegisterGroup"></asp:RequiredFieldValidator>
120: <br /><br />
121: <!--ValidationGroup="RegisterGroup"-->
122: <asp:Button ID="btnRegister" runat="server" Text="Register" ValidationGroup="RegisterGroup" OnClick="btnRegister_Click"/>
123: </fieldset>
124: <asp:Label ID="lblRegisterResult" runat="server"></asp:Label>
125: </div>
126: </form>
127: </body>
128: </html>
上面的代码中,注意两个组,虽然TextBox也有ValidationGroup属性,但是我们不必为TextBox也设置ValidationGroup,只需为验证控件和按钮设置验证组就可以了。在分了验证组以后,两个表单的行为互不干涉。
4. 禁用验证
所有的按钮控件Button, ImageButton, LinkButton都有一个CauseValidation属性,如果设置这个按钮的CauseValidation属性为false,那么当点击这个按钮时将绕过页面中的所有验证。
下面的代码中,采用一个取消按钮,当点击它时,不对表单进行验证,而是重定向到Default页面
1: <%@ Page Language="C#"%>
2: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
3: <script runat="server">
4: void btnCancel_Click(Object sender, EventArgs e)
5: {
6: Response.Redirect("~/Default.aspx");
7: }
8: </script>
9: <html xmlns="http://www.w3.org/1999/xhtml" >
10: <head id="Head1" runat="server">
11: <title>Show Disable Validation</title>
12: </head>
13: <body>
14: <form id="form1" runat="server">
15: <div>
16:
17: <asp:Label ID="lblFirstName" runat="server" Text="First Name:" AssociatedControlID="txtFirstName"></asp:Label>
18: <br />
19: <asp:TextBox ID="txtFirstName" runat="server"></asp:TextBox>
20: <asp:RequiredFieldValidator
21: ID="reqFirstName"
22: runat="server"
23: ControlToValidate="txtFirstName"
24: Text="(required)"
25: ></asp:RequiredFieldValidator>
26: <br />
27: <!--如果没有CausesValidation属性,RequiredFieldValidator控件在文本框未输入的情况下,阻止提交表单-->
28: <asp:Button ID="btnCancel" runat="server" Text="Cancel" OnClick="btnCancel_Click"/>
29:
30: </div>
31: </form>
32: </body>
33: </html>
5.使用RequiredFieldValidator控件
在前面的几个例子当中,已经大量使用了RequireFileldValidator控件,这个控件的作用就是来验证非空字符串。RequireFieldValidator控件还有一个属性IntialValue,这个属性用来指定除空字符串之外的默认值。例如,用RequireFieldValidator控件来验证DropDownList控件。
1: <%@ Page Language="C#"%>
2: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
3: <script runat="server">
4: void btnSubmit_Click(Object sender, EventArgs e)
5: {
6: if (Page.IsValid)
7: this.lblResult.Text = this.dropFavoriteColor.SelectedValue;//如果页面验证通过,显示用户选择的结果
8: }
9: </script>
10: <html xmlns="http://www.w3.org/1999/xhtml" >
11: <head id="Head1" runat="server">
12: <title></title>
13: </head>
14: <body>
15: <form id="form1" runat="server">
16: <div>
17:
18: <asp:Label ID="lblFavoriteColor" runat="server" Text="Favorite Color:"></asp:Label>
19: <br />
20: <asp:DropDownList ID="dropFavoriteColor" runat="server">
21: <asp:ListItem Text="Select Color" Value="none"></asp:ListItem>
22: <asp:ListItem Text="Red" Value="Red"></asp:ListItem>
23: <asp:ListItem Text="Green" Value="Green"></asp:ListItem>
24: <asp:ListItem Text="Blue" Value="Blue"></asp:ListItem>
25: </asp:DropDownList>
26: <!--指定了InitialValue为none,如果DropDownList中选中的是Value="none"的那一项,将会提示错误,这能够判断是否对DropDownList进行了选择-->
27: <asp:RequiredFieldValidator
28: ID="reqFavoriteColor"
29: runat="server"
30: Text="(required)"
31: InitialValue="none"
32: ControlToValidate="dropFavoriteColor"
33: ></asp:RequiredFieldValidator>
34: <br />
35: <asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click"/>
36: <hr />
37: <asp:Label ID="lblResult" runat="server"></asp:Label>
38:
39: </div>
40: </form>
41: </body>
42: </html>
6. 使用RangeValidator控件
RangeValidator控件用于验证表单的值是否位于某个范围之间,所以要为RangeValidator指定一个最小值和最大值。使用这个控件,必须得设置5个属性:
■ControlToValidate——要验证的控件
■Text——验证失败时的错误信息
■MinimumValue——最小值
■MaximumValue——最大值
■Type——所执行的比较类型:Type, Integer, Double, Date, Currency
下面的代码演示了在文本框中输入年龄时,必须输入5-100之间的数值。
1: <%@ Page Language="C#"%>
2: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
3: <script runat="server">
4: </script>
5: <html xmlns="http://www.w3.org/1999/xhtml" >
6: <head id="Head1" runat="server">
7: <title>Show RangeValidator</title>
8: </head>
9: <body>
10: <form id="form1" runat="server">
11: <div>
12: <asp:Label ID="lblAge" runat="server" Text="Age:" AssociatedControlID="txtAge"></asp:Label>
13: <br />
14: <asp:TextBox ID="txtAge" runat="server"></asp:TextBox>
15:
16: <asp:RequiredFieldValidator
17: ID="reqFieldAge"
18: runat="server"
19: Display="Dynamic"
20: ControlToValidate="txtAge"
21: Text="(Required)"></asp:RequiredFieldValidator>
22:
23: <!--RangeValidator必须属性:Type,MinimumValue,MaximumValue,ControlToValidate,Text-->
24: <asp:RangeValidator
25: ID="reqRangeAge"
26: runat="server"
27: Display="Dynamic"
28: Type="Integer"
29: MinimumValue="5"
30: MaximumValue="100"
31: ControlToValidate="txtAge"
32: Text="(Invalid Age)"></asp:RangeValidator>
33: <br /><br />
34: <asp:Button ID="btnSubmit" runat="server" Text="Submit" />
35:
36: </div>
37: </form>
38: </body>
39: </html>
7. 使用CompareValidator控件
CompareValidator控件可以执行三种不同类型的验证任务:
■ 验证类型。可以用它验证用户在表单字段中是否输入了正确的数据类型
■ 和固定值比较。和固定值之间的关系有:大于、大于等于、小于、小于等于、等于和不等于
■ 比较两个表单字段的值。比如验证用户在注册时,密码和重复密码是否相同。
CompareValidator6个重要的属性:
■ ControlToValidate——被验证的表单的ID
■ Text——错误时显示的文本
■ Type——比较的数据类型:String, Integer, Double, Date,Currency
■ Operator——所执行的比较类型:DataTypeCheck, Equal, GreaterThan, GreaterThanEqual, LessThan, LessThanEqual, NotEqual
■ ValueToCompare——所比较的固定值
■ ControlToCompare——所比较的控件的ID
验证数据类型代码清单:
1: <%@ Page Language="C#"%>
2: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
3: <script runat="server">
4: </script>
5: <html xmlns="http://www.w3.org/1999/xhtml" >
6: <head id="Head1" runat="server">
7: <title>Shoe Data Type Check</title>
8: </head>
9: <body>
10: <form id="form1" runat="server">
11: <div>
12: <asp:Label ID="lblBirthDate" runat="server" Text="Birth Date:" AssociatedControlID="txtBirthDate"></asp:Label>
13: <asp:TextBox ID="txtBirthDate" runat="server"></asp:TextBox>
14: <!--CompareValidator6个重要的属性
15: ControlToValidate——被验证的表单的ID
16: Text——错误时显示的文本
17: Type——比较的数据类型:String, Integer, Double, Date,Currency
18: Operator——所执行的比较类型:DataTypeCheck, Equal, GreaterThan, GreaterThanEqual, LessThan, LessThanEqual, NotEqual
19: ValueToCompare——所比较的固定值
20: ControlToCompare——所比较的控件的ID
21: -->
22: <asp:CompareValidator
23: runat="server"
24: ID="cmpBirthDate"
25: ControlToValidate="txtBirthDate"
26: Type="Date"
27: Operator="DataTypeCheck"
28: Text="(Invalid Date)"></asp:CompareValidator>
29: <br /><br />
30: <asp:Button ID="btnSubmit" runat="server" Text="Submit" />
31: </div>
32: </form>
33: </body>
34: </html>
和固定值比较代码清单:
1: <%@ Page Language="C#"%>
2: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
3: <script runat="server">
4: void Page_Load()
5: {
6: if(!Page.IsPostBack)
7: cmpDate.ValueToCompare = DateTime.Now.ToString("d");//获取当前时间,以当前时间作为比较值,在点击按钮时获取。
8: }
9: </script>
10: <html xmlns="http://www.w3.org/1999/xhtml" >
11: <head id="Head1" runat="server">
12: <title>Show Fixed Value</title>
13: </head>
14: <body>
15: <form id="form1" runat="server">
16: <div>
17: <asp:Label ID="lblDate" runat="server" Text="Date:" AssociatedControlID="txtDate"></asp:Label>
18: <asp:TextBox ID="txtDate" runat="server"></asp:TextBox>
19: <!--验证输入的时间是否大于当前时间-->
20: <asp:CompareValidator
21: ID="cmpDate"
22: runat="server"
23: ControlToValidate="txtDate"
24: Operator="GreaterThan"
25: Type="Date"
26: Text="(Date must be greater than now)"></asp:CompareValidator>
27: <br /><br />
28: <asp:Button ID="btnSubmit" runat="server" Text="Submit" />
29:
30: </div>
31: </form>
32: </body>
33: </html>
两个表单字段进行对比,代码清单:
1: <%@ Page Language="C#"%>
2: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
3: <script runat="server">
4: </script>
5: <html xmlns="http://www.w3.org/1999/xhtml" >
6: <head id="Head1" runat="server">
7: <title>Show Compare Values</title>
8: </head>
9: <body>
10: <form id="form1" runat="server">
11: <div>
12: <!--比较结束时间和起始时间,结束时间应当大于结束时间-->
13: <asp:Label ID="lblStartDate" runat="server" Text="Start Date:" AssociatedControlID="txtStartDate"></asp:Label>
14: <asp:TextBox ID="txtStartDate" runat="server"></asp:TextBox>
15: <br />
16: <asp:Label ID="lblEndDate" runat="server" Text="End Date:" AssociatedControlID="txtEndDate"></asp:Label>
17: <asp:TextBox ID="txtEndDate" runat="server"></asp:TextBox>
18: <asp:CompareValidator
19: ID="cmpDate"
20: runat="server"
21: ControlToValidate="txtEndDate"
22: ControlToCompare="txtStartDate"
23: Operator="GreaterThan"
24: Type="Date"
25: Text="(End date must be greater than start date)"></asp:CompareValidator>
26: <br /><br />
27: <asp:Button runat="server" ID="btnSubmit" Text="Submit"/>
28: </div>
29: </form>
30: </body>
31: </html>
8. 使用RegularExpressionValidator控件
使用这个控件,是用正则表达式来对表单进行验证,如果你比较熟悉正则表达式,那在对表单验证时将会非常有用。即使你不熟悉正则表达式,通过www.google.com.hk可以很容易找到常用的正则表达式。如果想快速入门正则表达式,可以看看这里:正则表达式30分钟入门教程。
下面的代码是一个简单的验证Email格式的例子:
1: <%@ Page Language="C#"%>
2: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
3: <script runat="server">
4: </script>
5: <html xmlns="http://www.w3.org/1999/xhtml" >
6: <head id="Head1" runat="server">
7: <title>Show RegularExpressionValidator</title>
8: </head>
9: <body>
10: <form id="form1" runat="server">
11: <div>
12: <asp:Label ID="lblEmail" runat="server" Text="Email:" AssociatedControlID="txtEmail"></asp:Label>
13: <asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
14: <asp:RegularExpressionValidator
15: ID="reqEmail"
16: runat="server"
17: ControlToValidate="txtEmail"
18: Text="(Invalid Email)"
19: ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"></asp:RegularExpressionValidator>
20: <br /><br />
21: <asp:Button runat="server" ID="btnSubmit" Text="Submit"/>
22: </div>
23: </form>
24: </body>
25: </html>
9.使用CustomValidator控件
如果前面的一些验证控件不能够满足你的需要,而你又不愿意使用复杂的正则表达式去验证表单,你可以考虑使用CustomValidator控件,它可能会帮你解决掉一些问题。
CustomValidator控件有三个重要的属性:
■ ControlToValidate
■ Text
■ ClientValidationFunction——这个属性关联一个客户端的javascript函数,可以调用这个函数来对表单进行验证。
CustomValidator控件还有一个服务器端的事件:
■ ServerValidate——CustomValidator控件执行验证时触发该事件。
假设想验证输入表单字段的长度,比如用户评论不得少于5个字符:
1: <%@ Page Language="C#"%>
2: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
3: <script runat="server">
4: //传给ServerValidate事件的第二个参数是ServerValidateEventArgs类的一个实例
5: protected void valComments_ServerValidate(object source, ServerValidateEventArgs args)
6: {
7:
8: if (args.Value.Length < 5)
9: args.IsValid = false;
10: else
11: args.IsValid = true;
12: }
13: </script>
14: <html xmlns="http://www.w3.org/1999/xhtml" >
15: <head id="Head1" runat="server">
16: <title>Show CustomValidator</title>
17: </head>
18: <body>
19: <form id="form1" runat="server">
20: <div>
21: <asp:Label ID="lblComments" runat="server" Text="Comments:" AssociatedControlID="txtComments"></asp:Label>
22: <asp:TextBox ID="txtComments" runat="server" Columns="30" Rows="5" TextMode="MultiLine"></asp:TextBox>
23: <asp:CustomValidator
24: ID="valComments"
25: runat="server"
26: ControlToValidate="txtComments"
27: Text="(Comments must more than 5 characters)" OnServerValidate="valComments_ServerValidate"></asp:CustomValidator>
28: <br /><br />
29: <asp:Button ID="btnSubmit" runat="server" Text="Submit" />
30:
31: </div>
32: </form>
33: </body>
34: </html>
ServerValidateEventArgs类有三个属性:
■ Value——被验证的表单字段的值
■ IsValid——验证成功或者失败
■ ValidateEmptyText——表示所验证的表单字段没有值时是否进行验证。如果为true,这个属性也能够验证表单字段是否非空。
ValidateEmptyText的一个例子,检验产品码必须为4个字符:
1: <%@ Page Language="C#"%>
2: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
3: <script runat="server">
4:
5: //如果没有设置ValidateEmptyText="true"这个属性,在表单字段为空的情况下,验证仍然是通过的
6: protected void valProductCode_ServerValidate(object source, ServerValidateEventArgs args)
7: {
8: if (args.Value.Length == 4)
9: args.IsValid = true;
10: else
11: args.IsValid = false;
12: }
13: </script>
14: <html xmlns="http://www.w3.org/1999/xhtml" >
15: <head id="Head1" runat="server">
16: <title>Show Validate Empty Text</title>
17: </head>
18: <body>
19: <form id="form1" runat="server">
20: <div>
21: <asp:Label ID="lblProductCode" runat="server" Text="Product Code:" AssociatedControlID="txtProductCode"></asp:Label>
22: <asp:TextBox ID="txtProductCode" runat="server"></asp:TextBox>
23: <!--ValidateEmptyText="true",对TextBox是否为空也进行验证-->
24: <asp:CustomValidator
25: runat="server"
26: ID="valProductCode"
27: ValidateEmptyText="true"
28: ControlToValidate="txtProductCode"
29: Text="(Product code must be 4 characters)"
30: OnServerValidate="valProductCode_ServerValidate"></asp:CustomValidator>
31: <br /><br />
32: <asp:Button ID="btnSubmit" runat="server" Text="Submit" />
33:
34: </div>
35: </form>
36: </body>
37: </html>
ServerValidate事件是一个服务端事件,只有在页面回传以后,才会执行这个事件进行验证,如果想要通过客户端进行验证,那就要用到前面提到的一个重要的属性ClientValidationFunction,采用客户端的javascript函数也能进行验证。
1: <%@ Page Language="C#"%>
2: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
3: <script runat="server">
4: //执行服务端验证
5: protected void valComments_ServerValidate(object source, ServerValidateEventArgs args)
6: {
7: if (args.Value.Length < 5)
8: args.IsValid = false;
9: else
10: args.IsValid = true;
11: }
12: </script>
13: <html xmlns="http://www.w3.org/1999/xhtml" >
14: <head id="Head1" runat="server">
15: <title>Show CustomValidator with JavaScript</title>
16: <script type="text/javascript">
17: //执行客户端验证
18: function valComments_ClientValidate(source, args)//这个函数同样接受连个参数,而且参数的属性和服务器端的参数属性写法是一致的
19: {
20: if (args.Value.length <5)
21: args.IsValid = false;
22: else
23: args.IsValid = true;
24: }
25: </script>
26: </head>
27: <body>
28: <form id="form1" runat="server">
29: <div>
30: <asp:Label ID="lblComments" runat="server" Text="Comments:" AssociatedControlID="txtComments"></asp:Label>
31: <asp:TextBox ID="txtComments" runat="server" Columns="30" Rows="5" TextMode="MultiLine"></asp:TextBox>
32: <asp:CustomValidator
33: ID="valComments"
34: runat="server"
35: ControlToValidate="txtComments"
36: Text="(Comments must be more than 5 characters)"
37: ClientValidationFunction="valComments_ClientValidate"
38: ></asp:CustomValidator>
39:
40: <br /><br />
41: <asp:Button ID="btnSubmit" runat="server" Text="Submit" />
42: </div>
43: </form>
44: </body>
45: </html>
CustomValidator控件和其他控件有一点点区别,这个区别就是它不一定要关联一个控件。我们可以不设置它的这个属性,例如下面这个页面中包含一个定时测试,如果用户回答问题的时间超过5秒,将提示用户回答太慢。
1: <%@ Page Language="C#"%>
2: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
3: <script runat="server">
4: void Page_Load()
5: {
6: if (!Page.IsPostBack)
7: ResetStartTime();
8: }
9:
10: //重新来过
11: protected void btnAgain_Click(object sender, EventArgs e)
12: {
13: ResetStartTime();
14: }
15:
16: //设置开始事件,并用Session变量存储起来
17: void ResetStartTime()
18: {
19: Session["StartTime"] = DateTime.Now;
20: }
21:
22: //判断用户回答时是否超时
23: protected void valAnswer_ServerValidate(object source, ServerValidateEventArgs args)
24: {
25: DateTime startTime = (DateTime)Session["StartTime"];
26: if (startTime.AddSeconds(5) > DateTime.Now)
27: args.IsValid = true;
28: else
29: args.IsValid = false;
30: }
31:
32:
33: </script>
34: <html xmlns="http://www.w3.org/1999/xhtml" >
35: <head id="Head1" runat="server">
36: <title></title>
37: </head>
38: <body>
39: <form id="form1" runat="server">
40: <div>
41: <asp:Label ID="lblQuestion"
42: runat="server"
43: Text="What was Aristotle's first name?"
44: AssociatedControlID="txtAnswer"></asp:Label>
45: <br />
46: <asp:TextBox
47: ID="txtAnswer"
48: runat="server"></asp:TextBox>
49: <!--这里并没有为CustomValidator控件提供ControlToValidate属性-->
50: <asp:CustomValidator
51: ID="valAnswer"
52: runat="server"
53: Text="(You answerd too slowly!)"
54: OnServerValidate="valAnswer_ServerValidate"></asp:CustomValidator>
55:
56: <br /><br />
57:
58: <asp:Button ID="btnSubmit"
59: runat="server"
60: Text="Submit" />
61: <asp:Button ID="btnAgain"
62: runat="server"
63: Text="Try Again!"
64: CausesValidation="false"
65: OnClick="btnAgain_Click" />
66:
67: </div>
68: </form>
69: </body>
70: </html>
10. 使用ValidationSummary控件
前面提到了ValidatioSummary控件,它的作用就是用来对验证的错误信息进行汇总,但是它不是通过验证控件的Text属性来显示错误,而是通过ErrorMessage属性来显示,ErrorMessage总是显示在ValidationSummary控件中的,Text是直接显示在页面中的。
1: <%@ Page Language="C#"%>
2: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
3: <script runat="server">
4: </script>
5: <html xmlns="http://www.w3.org/1999/xhtml" >
6: <head id="Head1" runat="server">
7: <title>Show ValidationSummary</title>
8: </head>
9: <body>
10: <form id="form1" runat="server">
11: <div>
12: <!--创建一个ValidationSummary控件-->
13: <asp:ValidationSummary
14: ID="ValidationSummary1"
15: runat="server" />
16:
17: <asp:Label
18: ID="lblFirstName"
19: runat="server"
20: Text="First Name:"
21: AssociatedControlID="txtFirstName"></asp:Label>
22: <br />
23: <asp:TextBox
24: ID="txtFirstName"
25: runat="server"></asp:TextBox>
26: <!--ErrorMessage-->
27: <asp:RequiredFieldValidator
28: ID="reqFirstName"
29: runat="server"
30: Text="(Required)"
31: ErrorMessage="First Name is required"
32: ControlToValidate="txtFirstName"></asp:RequiredFieldValidator>
33: <br /><br />
34:
35: <asp:Label
36: ID="lblLastName"
37: runat="server"
38: AssociatedControlID="txtLastName"></asp:Label>
39: <br />
40: <asp:TextBox
41: ID="txtLastName"
42: runat="server"
43: ></asp:TextBox>
44: <!--ErrorMessage-->
45: <asp:RequiredFieldValidator
46: ID="reqLastName"
47: runat="server"
48: Text="(Required)"
49: ErrorMessage="Last Name is required"
50: ControlToValidate="txtLastName"></asp:RequiredFieldValidator>
51:
52: <br /><br />
53:
54: <asp:Button
55: ID="btnSubmit"
56: runat="server"
57: Text="Submit"/>
58:
59: </div>
60: </form>
61: </body>
62: </html>
ValidationSummary控件还有几个比较有用的属性:
■ DisplayMode——用于指定如何格式化错误信息。可能的值:BulleList、List、SingleParagraph。
■ HeaderText——在验证汇总上方显示标题。
■ ShowMessageBox——通过弹出框来显示错误信息。
■ ShowSummary——bool值,用于隐藏或显示验证汇总。
下面的页面中,隐藏了验证错误时的汇总信息,而是通过弹出框来显示错误信息(不建议使用):
1: <%@ Page Language="C#"%>
2: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
3: <script runat="server">
4: </script>
5: <html xmlns="http://www.w3.org/1999/xhtml" >
6: <head id="Head1" runat="server">
7: <title>Show Summary Popup</title>
8: </head>
9: <body>
10: <form id="form1" runat="server">
11: <div>
12: <!--显示弹出框,不显示验证汇总信息-->
13: <asp:ValidationSummary
14: ID="ValidationSummary1"
15: ShowMessageBox="true"
16: ShowSummary="false"
17: runat="server" />
18:
19: <asp:Label
20: ID="lblFirstName"
21: runat="server"
22: Text="First Name:"
23: AssociatedControlID="txtFirstName"></asp:Label>
24: <br />
25: <asp:TextBox
26: ID="txtFirstName"
27: runat="server"></asp:TextBox>
28: <asp:RequiredFieldValidator
29: ID="reqFirstName"
30: runat="Server"
31: ErrorMessage="First Name is requeire"
32: ControlToValidate="txtFirstName"
33: Display="None"></asp:RequiredFieldValidator>
34:
35: <br /><br />
36:
37: <asp:Label
38: ID="lblLastName"
39: runat="Server"
40: Text="Last Name:"
41: AssociatedControlID="txtLastName"></asp:Label>
42: <br />
43: <asp:TextBox
44: ID="txtLastName"
45: runat="server"></asp:TextBox>
46: <asp:RequiredFieldValidator
47: ID="reqLastName"
48: runat="server"
49: ErrorMessage="Last Name is required"
50: ControlToValidate="txtLastName"
51: Display="None"></asp:RequiredFieldValidator>
52:
53: <asp:Button
54: ID="btnSubmit"
55: runat="server"
56: Text="Submit"/>
57:
58: </div>
59: </form>
60: </body>
61: </html>
11.创建自定义验证控件
BaseValidator是一个抽象的验证控件几类,以上的6个验证控件都是继承自它。要创建自定义的验证控件类,至少要继承BaseValidator类,复杂一点还要继承一些接口来实现自定义控件的事件。
继承BaseValidator类,需要实现它的抽象方法EvaluateIsValid,BaseValidator类还有一个很有用的方法GetControlValidationValue,用来获取被验证控件的值
这里我只以一个简单的自定义验证控件为例,一个验证表单字段长度的验证控件。
1: using System;
2: using System.Data;
3: using System.Configuration;
4: using System.Web;
5: using System.Web.Security;
6: using System.Web.UI;
7: using System.Web.UI.WebControls;
8: using System.Web.UI.WebControls.WebParts;
9: using System.Web.UI.HtmlControls;
10:
11: namespace ASP.NET_3.__Chapter3.App_Code
12: {
13: /// <summary>
14: /// 验证输入表单的长度
15: /// </summary>
16: public class LengthValidator : BaseValidator
17: {
18: //用户自定义表单字段值的最大长度
19: private int _maximumLength = 0;
20:
21: public int MaximumLength
22: {
23: get
24: {
25: return _maximumLength;
26: }
27: set
28: {
29: _maximumLength = value;
30: }
31: }
32:
33: //重写EvaluateIsValid方法
34: protected override bool EvaluateIsValid()
35: {
36: string value = this.GetControlValidationValue(this.ControlToValidate);//获取被验证的控件值
37: if(value.Length > _maximumLength)
38: return false;
39: else
40: return true;
41: }
42: }
43: }
使用LengthValidator这个验证控件
1: <%@ Page Language="C#" %>
2: <!--注意头部的标签前缀(TagPrefix)和命名空间不要写错了-->
3: <%@ Register TagPrefix="custom" Namespace="ASP.NET_3.__Chapter3.App_Code" %>
4: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
5: <html xmlns="http://www.w3.org/1999/xhtml" >
6: <head id="Head1" runat="server">
7: <title>Show Length Validator</title>
8: </head>
9: <body>
10: <form id="form1" runat="server">
11: <div>
12:
13: <asp:Label
14: id="lblComments"
15: Text="Comments:"
16: AssociatedControlID="txtComments"
17: Runat="server" />
18: <br />
19: <asp:TextBox
20: id="txtComments"
21: TextMode="MultiLine"
22: Columns="30"
23: Rows="2"
24: Runat="server" />
25:
26:
27: <custom:LengthValidator
28: id="valComments"
29: ControlToValidate="txtComments"
30: Text="(Must be less than 10 characters)"
31: MaximumLength="10"
32: Runat="server" />
33:
34: <br /><br />
35:
36: <asp:Button
37: id="btnSubmit"
38: Text="Submit"
39: Runat="server" />
40:
41: </div>
42: </form>
43: </body>
44: </html>