【问题标题】:No error message displayed for custom validator没有为自定义验证器显示错误消息
【发布时间】:2010-11-03 22:50:06
【问题描述】:

我要求需要多个字段之一。使用自定义验证器偶数触发,返回 false,但不显示错误消息并且表单验证。

我错过了什么?我尝试过使用和不使用 ValidationSummary。

谢谢!

<asp:CustomValidator ID="CustomValidator1" OnServerValidate="validatePhone" EnableClientScript="false" runat="server" ErrorMessage="Home or Cell Phone is Required" ></asp:CustomValidator>

<asp:ValidationSummary ID="ValidationSummary1" DisplayMode="BulletList"  runat="server" ForeColor="Red" Font-Size="X-Small" Font-Bold="true" />


protected void validatePhone(object sender, ServerValidateEventArgs e)
    {
        e.IsValid = string.IsNullOrEmpty(txtCellPhone.Text) && string.IsNullOrEmpty(txtHomePhone.Text) ? false : true;
    }

【问题讨论】:

    标签: asp.net validation


    【解决方案1】:

    您必须将 ControlToValidate 设置为某个 TextBox。

    <asp:CustomValidator ID="CustomValidator1" OnServerValidate="validatePhone" EnabEnableClientScript="false" runat="server" ErrorMessage="Home or Cell Phone is Required" ControlToValidate="txtHomePhone"/>
    

    【讨论】:

    • 设置 ControlToValidate 将不会验证控件是否为空。由于我正在验证多个控件,这将不起作用。
    【解决方案2】:

    查看this article。基本上你需要连接客户端验证。 在结束表单标记之前添加以下内容,根据需要更改控件名称:

    <%-- This configures the validator to automatically--%> 
    <%-- update when either of these controls is changed --%>
    <script type="text/javascript">
       <!--
          ValidatorHookupControlID("<%= MyControl1.ClientID %>", 
          document.getElementById["<%= CustomValidator1.ClientID %>"]);
          ValidatorHookupControlID("<%= MyControl2.ClientID %>", 
          document.getElementById["<%= CustomValidator1.ClientID %>"]);
       //-->
    </script>
    

    或者使用this control

    【讨论】:

      【解决方案3】:

      问题完全是我的错。在我的提交按钮上,我做的最后一件事是 Response.Redirect。消息即将出现,但随后出现了“谢谢”页面。现在只在 customvalidator 返回 true 时执行 Response.Redirect。

      【讨论】:

      • 只有在Page.IsValid = true 时才应该处理代码。这会检查 ValidationGroup 中的所有验证器是否有效。否则,您可以通过弄乱 JavaScript 来绕过验证。
      猜你喜欢
      • 1970-01-01
      • 2016-07-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-08
      • 1970-01-01
      • 1970-01-01
      • 2019-09-27
      相关资源
      最近更新 更多