C# CustomValidator

当各种验证控件的验证类型都不能满足需要时可以使用CustomValidator验证控件,通过自定义验证函数来验证。直接看例子

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="CustomValidator.aspx.cs" Inherits="WebApplication1.CustomValidator" %>

<!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>
    <style type ="text/css" >
        .red
        {
            color:Red ; 
        }
    </style>

    <script type ="text/javascript" >
        function cvComment_ServerValidate(source, args) {
            if (args.Value.Length > 10)
                args.IsValid = false;
            else
                args.IsValid = true;
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ValidationSummary ID="ValidationSummary1" runat="server" ShowMessageBox ="true"  ShowSummary ="true"  />
        <asp:Label runat ="server" Text ="comments:" AssociatedControlID ="txtComment"></asp:Label>
        <br />
        <asp:TextBox ID ="txtComment" runat ="server" Rows ="5" Columns ="30" TextMode ="MultiLine" ></asp:TextBox>
        <asp:CustomValidator ID ="cvComment" runat ="server"  ValidateEmptyText ="false" 
            ControlToValidate ="txtComment" Text ="Comments must less than 10 characters" ErrorMessage ="Comments must less than 10 characters."  Display ="Dynamic"  CssClass ="red"  
            onservervalidate="cvComment_ServerValidate" 
            ClientValidationFunction="cvComment_ServerValidate" ></asp:CustomValidator>
        <asp:RequiredFieldValidator ID ="reqComment" runat ="server" Text ="(Required)" Display ="Dynamic"  ErrorMessage ="Comments is required."  CssClass ="red" ControlToValidate ="txtComment"></asp:RequiredFieldValidator>
            <br />
        <asp:Button ID="btnSummit" runat="server" 
            Text="Summit" />
        <br />

    </div>
    </form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication1
{
    public partial class CustomValidator : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void cvComment_ServerValidate(object source, ServerValidateEventArgs args)
        {
            if (args.Value.Length > 10)
                args.IsValid = false;
            else
                args.IsValid  = true;
        }

    }
}

通过在CustomValidator控件的servervalidate事件编写验证代码实现控件的服务器端验证。args.Value表示验证的表单字段的值,args.IsValid表示验证成功或者失败

ClientValidationFunction属性设置客户端验证脚本,服务器端事件处理函数和客户端脚本相同,不同的是使用的语言不一样。

ValidationSummary控件可以显示所有验证控件错误信息,ShowMessageBox表示是否弹窗,默认为false ;ShowSummary表示是否在页面中显示验证信息,比如设置了弹窗可以不在页面中再次显示错误信息可以设置ShowSummary='false'.

每个验证控件都有ErrorMessage、和Text两个属性,区别在于ErrorMessage用于在ValidationSummary显示,而Text在具体的验证控件中显示,所以一般情况下ErrorMessage要能识别有错误的表单字段,而Text字段一般要进来简短。

注意:CustomValidator有验证错误时并不像其他验证控件(如RequiredFieldValidator)一样阻止页面提交。

CustomValidator中的ControlToValidate并不是必须的,比如

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %>

<!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>
    <p>你有5秒钟回答如下问题</p>
        <asp:Label ID="Label1" runat="server" Text="爱因斯坦是穿越者吗?"></asp:Label><br />
        <asp:TextBox ID="txtAnswer" runat="server" Rows ="5" Columns ="30" TextMode ="MultiLine" ></asp:TextBox>
        <asp:CustomValidator runat ="server" Text ="你回答太慢了!" 
            onservervalidate="Unnamed1_ServerValidate"></asp:CustomValidator>
        <br />
        <asp:Button ID="btnSummit" runat="server" 
            Text="Summit" />
    </div>
    </form>
</body>
</html>
View Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication1
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if(!IsPostBack)
                Session["startTime"] = DateTime.Now;
        }

        protected void Unnamed1_ServerValidate(object source, ServerValidateEventArgs args)
        {
            DateTime startTime =(DateTime)Session["startTime"];
            if (startTime.AddSeconds(5) > DateTime.Now)
                args.IsValid = true;
            else
                args.IsValid = false;
        }
    }
}
View Code


原文地址:https://www.cnblogs.com/lidaying5/p/10864974.html