验证发生前无法调用 Page.IsValid。应在 CausesValidation=True 且已启动回发的控件的事件处理程序中查询它,或在调用 Page.Validate 后查询。
<%@ Page Language="C#"%>
<Script Language="C#" Runat="Server">
public void Page_Load(Object src,EventArgs e)
{
if(Page.IsPostBack)
{
Page.Validate();
if(Page.IsValid)
{
show.Text = "已经通过验证";
}
else
{
show.Text = "没有通过验证";
}
}
}
</script>
<html>
<head>
<title></title>
</head>
<body>
<form runat="server">
<table>
<tr><td colspan=2 align="center"><b>RequiredFieldValidator控件演示
</b></td></tr>
<tr>
<td>姓名:</td>
<td><asp:TextBox id="name" runat="server" />*
<asp:RequiredFieldValidator id="rfv1" runat="server"
ControlToValidate="name"
Display="Static"
>(请填写姓名)
</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>年龄:</td>
<td><asp:TextBox id="age" runat="server" />*
<asp:RequiredFieldValidator id="rfv2" runat="server"
ControlToValidate="age"
Display="Static"
>(请填写年龄)
</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td><asp:Button Text="提交" runat="server" /></td>
<td></td>
</tr>
</table>
<hr>
<asp:Label id="show" ForeColor="red" runat="server" />
</form>
</body>
</html>