【问题标题】:How to tell which RequiredFieldValidator failed如何判断哪个RequiredFieldValidator 失败了
【发布时间】:2008-10-16 13:08:12
【问题描述】:

我的 aspx 页面上有多个 RequireFieldValidators。

在后端 (C#) 上,我希望能够明确指出哪个控件无效,以便我可以将样式应用于该控件。 我使用 Page.IsValid 方法来查看整个页面是否通过了验证,但我需要具体知道哪个控件失败了。

【问题讨论】:

    标签: c# .net validation


    【解决方案1】:

    正如其他人所提到的,您需要循环页面的验证器集合并检查它们的状态。 MSDN has examples here.

    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
    

    如果结束

    【讨论】:

      【解决方案2】:

      所有 Validator 都被添加到页面的 ValidatorCollection(属性 Page.Validators)中。

      您可以遍历此集合以手动验证每个控件。

      调用方法IValidator.Validate();

      【讨论】:

        【解决方案3】:

        根据内存,在调用 Page.Validate() 之后,您可以检查各个验证器以查看哪些是有效的,在验证器上使用 IsValid。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-03-23
          • 1970-01-01
          • 1970-01-01
          • 2013-10-09
          • 2015-03-29
          • 2010-11-02
          相关资源
          最近更新 更多