CustomValidator自定义控件有2种方式来进行验证:
第一种(客户端进行验证):ClientValidationFunction属性调用客户端JS的代码来进行验证,参数source为CustomValidator控件对象,参数args为CustomValidator控件传递过来的相关数据。
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="CustomDefault.aspx.cs" Inherits="第3章_自定义验证控件_CustomDefault" %>
<!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 type="text/javascript">
function myfun(source,args)
{
//注意大小写
if(args.Value.length < 6 || args.Value.length > 10)
{
//window.alert(source.id);
//window.alert(source.errormessage);
//window.alert(args.Value);
args.IsValid = false; //验证未通过
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:CustomValidator ID="CustomValidator1" runat="server" ControlToValidate="TextBox1"
ErrorMessage="长度应大于6位小于10位!" ClientValidationFunction="myfun">
</asp:CustomValidator>
<asp:Button ID="Button1" runat="server" Text="Button" />
</div>
</form>
</body>
</html>
第二种(服务器端进行验证):
.aspx文件代码:
<asp:CustomValidator ID="CustomValidator1" runat="server" ControlToValidate="TextBox1"
ErrorMessage="长度应大于6位小于10位!" onservervalidate="CustomValidator1_ServerValidate1">
</asp:CustomValidator>
.cs文件代码:
protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
{
if (args.Value.Length > 10)
args.IsValid = false;
else
args.IsValid = true;
}