2012-04-16 51 views
0

我有一个用户控件,它有一个布尔IsValidDate属性。如何使用CustomValidator检查此值并在属性的值为false时返回其错误消息?ASP.NET - 使CustomValidator检查控件的属性

+0

可能这就是你要找的东西http://stackoverflow.com/questions/939802/date-validation-with-asp-net-validator – coder 2012-04-16 07:50:15

回答

1

如果你的用户控件看起来是这样的:

<%@ 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

相关问题