在ASP.NET客户端验证checkboxlist

时间:2014-04-05 23:16:37

标签: javascript asp.net validation

我尝试使用以下代码验证我的复选框列表,但由于某种原因它每次都给我错误消息,即使选中了正确数量的复选框,我也无法找到任何任何骚扰,任何人都可以找到我的错误做错了?

<asp:CheckBoxList ID="CheckBoxList" runat="server">
</asp:CheckBoxList>

<asp:CustomValidator ID="CustomValidator1" runat="server" ClientValidationFunction="validate" ErrorMessage="choose a role, not more than 2"
        ValidationGroup="CreateUserWizard1"></asp:CustomValidator>

    <script type="text/javascript">
    function validate(source, arguments) {
        arguments.IsValid = false;

        var checklist = document.getElementById("CheckBoxList");
        if (checklist == null) return;

        var elements = checklist.getElementsByTagName("INPUT");
        if (elements == null) return;

        var checkBoxCount = 0;
        for (i = 0; i < elements.length; i++) {
            if (elements[i].checked) checkBoxCount++;
        }
        arguments.IsValid = (checkBoxCount > 0 || checkBoxCount <= 2);
    }
</script>

脚本是从堆栈上的类似问题中获取的,我无法弄清楚“输入”与什么相关?

1 个答案:

答案 0 :(得分:0)

您必须将检查列表框的呈现ID设为:

var checklist = document.getElementById("<%=CheckBoxList.ClientID%>");

您还可以阅读:Accessing control client name and not ID in ASP.NET