自定义验证程序不适用于文本框

时间:2013-07-31 02:37:29

标签: c# asp.net customvalidator server-side-validation

我正在学习如何使用自定义验证器进行服务器端验证,但我似乎无法使其正常工作。每当我单击按钮,文本框为空时,错误消息都不会显示。我做错了什么?

<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>

<asp:CustomValidator ID="CustomValidator1" ControlToValidate="TextBox1"
     OnServerValidate="CustomValidator1_ServerValidate" ValidationGroup="ValidateGp"
     ErrorMessage="This is a custom error validator" runat="server"/>

<asp:Button ID="Button1" runat="server" Text="Button" ValidationGroup="ValidateGp"/>

protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
{
    if (args.Value.Equals(string.Empty))
    {
        args.IsValid = false;
    }
    else
    {
        args.IsValid = true;
    }
}

2 个答案:

答案 0 :(得分:4)

您错过了

的ValidateEmptyText =“true”
<asp:CustomValidator ID="CustomValidator1"
                    ValidateEmptyText="true" runat="server" ValidationGroup="ValidateGp" ErrorMessage="This is a custom error validator" ControlToValidate="TextBox1" OnServerValidate="CustomValidator1_ServerValidate"></asp:CustomValidator>

答案 1 :(得分:0)

除了强制进行空验证之外,在某些情况下,空TextBox是有效的(!),我建议您捕获TextBox更改事件并在那里强制Page.Validate()