CustomValidator控件具体实现客户端验证,服务器验证和混合式验证三种模式
1. 客户端验证
aspx
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
<script>
function clientValidate(source, args)
{
if ((args.Value % 2) == 0)
args.IsValid = true;
else
args.IsValid = false;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
数值: <asp:TextBox ID="txtInput" runat="server"></asp:TextBox>
<asp:CustomValidator ID="cvInput" runat="server" ErrorMessage="CustomValidator" ControlToValidate="txtInput" ClientValidationFunction="clientValidate">不是一个偶数!</asp:CustomValidator>
<br />
<asp:Button ID="btnSubmit" runat="server" Text="确定" OnClick="btnSubmit_Click" OnClientClick="btnSubmit_Click" />
<asp:Label ID="lblMsg" runat="server" ></asp:Label>
</div>
</form>
</body>
.cs
protected void btnSubmit_Click(object sender, EventArgs e)
{
if(Page.IsValid)
{
lblMsg.Text = "验证通过";
}
}
服务器验证
aspx
<div>
数值: <asp:TextBox ID="txtInput" runat="server" OnTextChanged="txtInput_TextChanged"></asp:TextBox>
<asp:CustomValidator ID="cvInput" runat="server" ErrorMessage="CustomValidator" ControlToValidate="txtInput" OnServerValidate="cvInput_ServerValidate">不是一个偶数!</asp:CustomValidator>
<br />
<asp:Button ID="btnSubmit" runat="server" Text="确定" OnClick="btnSubmit_Click" OnClientClick="btnSubmit_Click" />
<asp:Label ID="lblMsg" runat="server" ></asp:Label>
</div>
.cs
protected void btnSubmit_Click(object sender, EventArgs e)
{
if(Page.IsValid)
{
lblMsg.Text = "验证通过";
}
}
protected void cvInput_ServerValidate(object source, ServerValidateEventArgs args)
{
int value = int.Parse(args.Value);
if((value%2)==0)
{
args.IsValid = true;
}
else
{
args.IsValid = false;
}
}