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

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

cdlcidditAsked:
Who is Participating?
 
Pawan KumarDatabase ExpertCommented:
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
0
 
cdlcidditAuthor 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.
0
 
cdlcidditAuthor Commented:
Great answer for just basic asp.net checkboxlist validation.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.