How can I make a required field validator for a asp.net checkboxlist?

cdlciddit
cdlciddit used Ask the Experts™
on
Hello. I have a checkbox list. I want to make it required.  Meaning I want the user to check at least one box in the list.  None of the required field validators work for me.  I also tried doing a javascript validator but I couldn't get that to work.  This is my checboxlist code:

<asp:CheckBoxList ID="cblEduAssistPlans" runat="server" SelectedIndexChanged="cblEduAssistPlans_SelectedIndexChanged" AutoPostBack="true">
                       <asp:ListItem>Individualized education program (IEP)</asp:ListItem>
                       <asp:ListItem>Individualized Family Service Plan (IFSP)</asp:ListItem>
                       <asp:ListItem>504 Plan</asp:ListItem>
                       <asp:ListItem>Other</asp:ListItem>
                   </asp:CheckBoxList>

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Database Expert
Awarded 2016
Top Expert 2016
Commented:
You need to add few more things-

1. Add a custom validator
<asp:CustomValidator ID="CustomValidator1" ErrorMessage="Select at least one item from the list."
    ForeColor="Red" ClientValidationFunction="ValidateCheckBoxList" runat="server" />

Open in new window


2. Add a javascript function
<script type="text/javascript">
    function ValidateCheckBoxList(sender, args) {
        var checkBoxList = document.getElementById("<%=cblEduAssistPlans.ClientID %>");
        var checkboxes = checkBoxList.getElementsByTagName("input");
        var isValid = false;
        for (var i = 0; i < checkboxes.length; i++) {
            if (checkboxes[i].checked) {
                isValid = true;
                break;
            }
        }
        args.IsValid = isValid;
    }
</script>

Open in new window


if you need to refer the entire steps please refer - https://www.aspsnippets.com/Articles/Validate-ASPNet-CheckBoxList-at-least-one-CheckBox-checked-using-Custom-Validator.aspx

Author

Commented:
Hello @Pawan Kumar.  That worked perfectly.  Thanks so much for your help.  I thought that I had to do a custom validator OR a javascript function.  I wasn't aware to use them both together.

Author

Commented:
Great answer for just basic asp.net checkboxlist validation.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial