CustomValidator 是一个提供灵活验证方式的控件,它也能在客户端和服务器端验证,分别提供了两种验证的方法原型:
服务器端验证:
onservervalidate="CustomValidator1_ServerValidate"
客户端验证(js):
function ValidationFunctionName(source, arguments)
论对于客户端验证还是服务器端验证,设置通过验证的办法就是将第二个参数的IsValid属性设置为true即可,反之设置为false。需要注意的是验证控件里面有个ValidateEmptyText属性,设为true时验证空,否则不验证。
客户端验证(js)
前端代码:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script language="javascript" type="text/javascript">
function Check(source,args)
{
var obj=document.getElementById("TextBox1");
if(obj.value=="1")
{
args.IsValid = true;
}
else {
args.IsValid=false;
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:CustomValidator ID="CustomValidator1" runat="server"
ControlToValidate="TextBox1" ErrorMessage="*"
ValidateEmptyText="True" ClientValidationFunction="Check"></asp:CustomValidator>
</div>
</form>
</body>
</html>服务器端验证:
前端代码
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:CustomValidator ID="CustomValidator1" runat="server"
ControlToValidate="TextBox1" ErrorMessage="CustomValidator"
ValidateEmptyText="True" onservervalidate="CustomValidator1_ServerValidate"></asp:CustomValidator>
</div>
</form>
</body>
</html>后端代码:
protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
{
if (TextBox1.Text == "a")
{
args.IsValid = true;
//执行相应操作
}
else
{
args.IsValid = false;
}
}
本文详细介绍了ASP.NET中的CustomValidator控件,它提供了灵活的验证功能,支持客户端和服务器端验证。在服务器端,通过onservervalidate属性进行验证;在客户端,可以自定义JavaScript函数进行验证。示例代码展示了如何在前端实现验证。

427

被折叠的 条评论
为什么被折叠?



