1

Im trying to validate my checkbox list with the following code, but for some reason it gives me the errormessage every time, even if the right amount of checkboxes are checked, and I cant find any sulotions anywhere, can anyone spot what Im doing wrong?

<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>

the script is taken from a similar question on stack, and I can't really figure out what "INPUT" relates to?

Green_qaue
  • 3,561
  • 11
  • 47
  • 89

1 Answers1

0

You must get the rendered id of your check list boxes as:

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

you can also read: Accessing control client name and not ID in ASP.NET

Community
  • 1
  • 1
Aristos
  • 66,005
  • 16
  • 114
  • 150