【问题标题】:How do you determine which validator failed?你如何确定哪个验证器失败了?
【发布时间】:2011-10-17 13:54:11
【问题描述】:

我正在处理一个页面,我得到一个 Page.IsValid = false 并且我正在尝试确定哪个控件导致了验证问题。

【问题讨论】:

    标签: asp.net controls validation


    【解决方案1】:

    接受的答案允许您找到失败的验证器的验证消息。如果您想查找未通过验证的控件的 ID,可以通过将验证器转换为公开 ControlToValidate 属性的 BaseValidator 来获得它。例如:

    For Each v As BaseValidator In Page.Validators
        If Not v.IsValid Then
            ' You can see the control to validate name and error message here.
            Debug.WriteLine(v.ControlToValidate)
            Debug.WriteLine(v.ErrorMessage)
        End If
    Next
    

    【讨论】:

      【解决方案2】:

      感谢 Steven 提供此答案,但我必须对其进行一些更改才能使其正常工作,因为 this.Validators.Where() 有一些问题。

      using System.Linq;
      
      List<IValidator> errored = this.Validators.Cast<IValidator>().Where(v => !v.IsValid).ToList();
      

      【讨论】:

      • 它没有像@Steven 所说的那样工作,但这个答案是完美的。只需更改 Pagethis。谢谢
      • 我使用的是 Page.Validators 而不是 this.Validators
      • Page.Validators 对我不起作用.. 是的,有人还在使用 WebForms... bleh。但是这个答案很好用。谢谢+1
      • 基于这个答案,我使用以下代码来识别无效的验证器:'if (Page.IsValid) { // do something } else { // page is not valid List invalides = this.Validators.Cast().Where(v => !v.IsValid).ToList(); foreach (var invalides) { Debug.WriteLine(invalid.ErrorMessage); } }'
      【解决方案3】:

      要检查哪个 Validator 被触发,只需检查 Firebug 中的 HTML,如果任何 Validator 没有 display:none; 属性或在其属性中具有 visibility:visible,那么它就是导致 @ 987654325@false.

      【讨论】:

        【解决方案4】:

        在代码 (page_load) 中,您可以这样做:
        (根据 MSDN:http://msdn.microsoft.com/en-US/library/dh9ad08f%28v=VS.80%29.aspx

        If (Me.IsPostBack) Then
            Me.Validate()
            If (Not Me.IsValid) Then
                Dim msg As String
                ' Loop through all validation controls to see which 
                ' generated the error(s).
                Dim oValidator As IValidator
                For Each oValidator In Validators
                    If oValidator.IsValid = False Then
                        msg = msg & "<br />" & oValidator.ErrorMessage
                    End If
                Next
                Label1.Text = msg
            End If
        End If
        

        在标记中,您可以...

        • 您可以在验证器上添加“文本”(如 星号...)
        • 或者使用 validation_summary 控件(需要在验证器上显示错误消息)...

        【讨论】:

        • 或简称this.Validators.Where(v =&gt; !v.IsValid)
        • @Steven -- 我一直想了解这一点 -- 不过非常酷 -- 你应该为此获得荣誉。
        • 实际上很容易给我积分。只需点击我评论左侧的“向上箭头”即可;-)。
        • @Steven_ 这不会编译,因为 ValidatorCollection 没有实现 IEnumerable&lt;IValidator&gt; 但你可以使用 var v = Validators.Cast&lt;IValidator&gt;().Where(v =&gt; !v.IsValid);
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-05-06
        • 1970-01-01
        • 1970-01-01
        • 2015-08-27
        • 1970-01-01
        • 1970-01-01
        • 2011-10-06
        相关资源
        最近更新 更多