【问题标题】:Custom Validator not working for textbox自定义验证器不适用于文本框
【发布时间】:2013-07-31 02:37:28
【问题描述】:

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

<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;
    }
}

【问题讨论】:

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


【解决方案1】:

你错过了 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>

【讨论】:

    【解决方案2】:

    作为强制空验证的替代方案,因为在某些情况下空的 TextBox 是有效的 (!),我建议您捕获 TextBox 更改事件并在那里强制 Page.Validate()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多