<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="RequiredFieldValidator.aspx.cs" Inherits="RequiredFieldValidator.RequiredFieldValidator" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
</head>
<body>
<h1>
Bug Reporter
</h1>
<form id="form1" runat="server">
<table>
<tr>
<td align="center" colspan="3">
<asp:Label ID="Label1" runat="server" Text="please report your bug here" ></asp:Label>
</td>
</tr>
以上包括一个控件Label。
<tr>
<td>book</td>
<td>
<asp:DropDownList ID="DropDownList1" runat="server">
<asp:ListItem>--please pick A book--</asp:ListItem>
<asp:ListItem>learning</asp:ListItem>
</asp:DropDownList>
</td>
<td>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="please choose a book"
ControlToValidate="DropDownList1" Display="Static" InitialValue="--please pick A book--">
</asp:RequiredFieldValidator>
</td>
</tr>
以上包括两个控件 一个为DropDownList,一个为RequiredFieldValidator。RequiredFieldValidator最重要的属性就是ControlToValidate和ErrorMessage,前者用于识别要验证的控件,后者用于包含一个文本信息,当控件在列表中没有被选中时该信息就会显示出来,或者选中值与InitialValue属性值相同时也会显示这个信息。
RequiredFieldValidator还有一个Display属性,被设置为"static",该值告诉ASP.NET无论显示信息与否,都会为该控件在页面中分配显示信息的空间。如果设置为"Dynamic",只有在错误信息要显示时才分配空间。
<tr>
<td>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
</td>
</tr>
</table>
</form>
</body>
</html>
运行该页面然后不做任何操作,直接点击button按钮,每个被验证的控件会被检查,然后显示出错误信息。
一旦发生验证,当服务器端有任何验证发生时ASP.NET会回发到服务器。Page的IsValid属性值取决于每个需要验证的控件是否有效,如果验证通过,
Page的IsValid会被设置成true。