您可以通過擴展的CustomValidator類這樣
namespace CustomValidation
{
public class MyValidator : CustomValidator
{
protected override bool OnServerValidate(string value)
{
bool baseresult = base.OnServerValidate(value);
if (baseresult && value == "TestValue")
return true;
return false;
}
protected override void AddAttributesToRender(HtmlTextWriter writer)
{
base.AddAttributesToRender(writer);
}
protected override bool ControlPropertiesValid()
{
return base.ControlPropertiesValid();
}
protected override bool EvaluateIsValid()
{
return base.EvaluateIsValid();
}
}
}
而在你的aspx頁面創建自己的驗證剛纔添加的控制 -
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %>
<%@ Register TagPrefix="mytag" Namespace="CustomValidation" Assembly="WebApplication1"%>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<mytag:MyValidator ErrorMessage="Testing" ControlToValidate="txtBox" runat="server" />
<asp:TextBox runat="server" ID="txtBox"></asp:TextBox>
<asp:Button Text="Test Button" runat="server" ID="btnTest" OnClick="btnTest_Click" />
</div>
</form>
</body>
</html>
而且你OnServerValidate將在頁面調用。 IsValid
namespace WebApplication1
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnTest_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
}
}
}
}
謝謝!是的,這是我需要做的。 – swap000
很高興知道。 –