【发布时间】:2012-04-27 13:27:09
【问题描述】:
我有一个用户控件,它有一个 bool IsValidDate 属性。如果该属性的值为 false,如何使用 CustomValidator 来检查该值并返回其错误消息?
【问题讨论】:
-
可能这就是你要找的东西stackoverflow.com/questions/939802/…
我有一个用户控件,它有一个 bool IsValidDate 属性。如果该属性的值为 false,如何使用 CustomValidator 来检查该值并返回其错误消息?
【问题讨论】:
如果您的用户控件看起来像这样:
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="MyDateUserControl.ascx.cs" Inherits="CustomValidation.MyDateUserControl" %>
My custom user control
<asp:TextBox runat="server" ID="DateTextBox" />
<asp:CustomValidator runat="server" ValidateEmptyText="true" ID="DateCustomValidator" ControlToValidate="DateTextBox" OnServerValidate="DateCustomValidator_ServerValidate" ErrorMessage="The date is not valid" />
<asp:Button ID="SubmitButton" runat="server" Text="Submit" />
然后在你的代码隐藏中你可以使用:
public bool IsValidDate
{
get
{
DateTime temp;
return DateTime.TryParse(DateTextBox.Text, out temp);
}
}
protected void DateCustomValidator_ServerValidate(object source, ServerValidateEventArgs args)
{
args.IsValid = IsValidDate;
}
如果您不希望自定义验证器成为用户控件的一部分,则必须在 IsValidDate 前面加上用户控件的名称。
【讨论】: