【问题标题】:Custom Validator Not Firing (No error message, but no validation)自定义验证器未触发(没有错误消息,但没有验证)
【发布时间】:2011-01-17 12:37:59
【问题描述】:

我有一个自定义验证器:

 <asp:CustomValidator ID="QuestionValidator" runat="server" ErrorMessage="Please select an option" ClientValidationFunction="QuestionValidator_ServerValidate" OnServerValidate="QuestionValidator_ServerValidate" ValidateEmptyText="true"></asp:CustomValidator> 

我有一个数据列表提供的问题列表,我需要确保用户选择每个问题的答案。然后我有我的验证功能:

Protected Sub QuestionValidator_ServerValidate(ByVal source As Object, ByVal args As ServerValidateEventArgs)
    Dim SelectedItem As Boolean = False
    For Each c As Control In Page.Master.FindControl("form1").Controls
        If TypeOf c Is RadioButton Then
            Dim rb As RadioButton = DirectCast(c, RadioButton)
            If rb.GroupName = "AnswerOptions" AndAlso rb.Checked = True Then
                SelectedItem = True
            End If
        End If
    Next
    args.IsValid = SelectedItem
End Sub

<script type="text/javascript" language="javascript">  
   function QuestionValidator_ServerValidate() {   
        return true;   
    }   
</script>  

当我运行页面时,没有验证,也没有错误消息。请你指出我哪里出错了,我怀疑是Page.Master.FindControl("form1").Controls

我之前通过 form1.controls 循环通过控件完成了此类验证,但由于页面使用通过母版页传递的表单,因此无法使用。

【问题讨论】:

  • 这应该是客户端验证吗?我在某些浏览器上验证时遇到问题
  • 如果可能的话,两者都没有工作

标签: asp.net vb.net validation master-pages findcontrol


【解决方案1】:

您的代码可能存在缺陷。因为根据逻辑,如果您页面上的 50 个单选按钮中只有一个被选中,您的验证将通过。此外,所有 RB 的组名对于每个项目都是相同的。不确定 ASP.NET 是否重命名了这些问题,如果没有,则所有问题都归为一组。

对于循环部分,您可以循环遍历 DataList.Items 集合,而不是遍历表单上的所有控件: 暗淡项目为 DataListItem

For Each item In  DataList1.Items
   Dim ctrl As Control
   For Each ctrl In  item.Controls
         'do your rb state check here       
   Next ctrl
Next item

【讨论】:

    【解决方案2】:

    我会尝试遍历“Page.NamingContainer”或“Page.Controls”,看看效果如何。

    【讨论】:

    • 我也试过 Page.Controls (它给了我同样的结果)。如果我更改为 page.namingcontainer.controls,我会得到一个 IOORE。谢谢
    【解决方案3】:

    也许我错过了什么,但你不应该在自定义验证器中设置属性 ControlToValidate="ID_of_the_control_to_validate" 吗?

    【讨论】:

      【解决方案4】:

      我认为您需要为 CustomValidator 和 Validaiton 过程中涉及的所有控件提供 ValidationGroup

      【讨论】:

        猜你喜欢
        • 2021-07-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-06-04
        • 2020-12-28
        • 2014-06-11
        • 2015-01-08
        相关资源
        最近更新 更多