CustomValidator控件使用

验证要求:1 对一个输入进行多方面的验证 2 对checkboxlist进行至少选择一项的验证

1 对一个输入进行多方面的验证(采用客户端验证)

举例代码:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default4.aspx.cs" Inherits="Default4" %>
<!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 src="simpletree/jquery-1.4.2.js" type="text/javascript"></script>
<script language="javascript" type="text/javascript">
//验证输入
function ValidateInput(source,args)
{
args.IsValid
=true;

if (args.Value.length ==0)
{
$(
"#" + source.id).html("不能为空");
args.IsValid
=false;
}
else if (!args.Value.match(/^[0-9]*[1-9][0-9]*$/))
{
$(
"#" + source.id).html("必须为正整数");
args.IsValid
=false;
}
else
{
if (args.Value < 1 || args.Value > 365)
{
args.IsValid
=false;
$(
"#" + source.id).html("必须在1到365之间");
}
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:TextBox ID="txtMinSpace" runat="server"></asp:TextBox>
<asp:CustomValidator ID="dfdf" runat="server"
ControlToValidate
="txtMinSpace"
SetFocusOnError
="True"
ClientValidationFunction
="ValidateInput"
ErrorMessage
="Requi"
ValidateEmptyText
="true"
Display
="Dynamic">
</asp:CustomValidator>
<br />
<asp:Button ID="test" runat="server" Text="提交" onclick="test_Click"/>
</form>
</body>
</html>

 注意事项:ValidateEmptyText需要验证空值时需要设置此属性,否则不启作用。

2 对checkboxlist进行至少选择一项的验证(采用客户端验证)

举例代码:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default4.aspx.cs" Inherits="Default4" %>
<!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 src="simpletree/jquery-1.4.2.js" type="text/javascript"></script>
<script language="javascript" type="text/javascript">
//验证选择
function ValidateCheckList(source,args)
{
args.IsValid
=true;

if($("#<%=cblAction.ClientID%> input[@type=checkbox]:checked").size() == 0)
args.IsValid
=false;
}
</script>
</head>
<body>
<form id="form1" runat="server">

<asp:CheckBoxList ID="cblAction" runat="server">
<asp:ListItem Value="1" Selected="True">选项1</asp:ListItem>
<asp:ListItem Value="2" Selected="True">选项1</asp:ListItem>
<asp:ListItem Value="3" Selected="True">选项1</asp:ListItem>
</asp:CheckBoxList>
<asp:CustomValidator ID="ctvAction" runat="server"
ErrorMessage
="至少选择一个" ClientValidationFunction="ValidateCheckList" Display="Dynamic" >
</asp:CustomValidator>
<br />
<asp:Button ID="test" runat="server" Text="提交" onclick="test_Click"/>
</form>
</body>
</html>

原文地址:https://www.cnblogs.com/neekerss/p/1822274.html