Friday, February 27, 2015

Validate CheckboxList in ASP.NET on Client Side using Javascript

We can Validate CheckboxList using the CustomValidator on Client side and server-side as well.

Our approach here will be validating the checkboxlist on client-side.

1. Add the CheckboxList with some items as below.

<asp:CheckBoxList ID="CheckBoxList1" runat="server">
          <asp:ListItem>A</asp:ListItem>
          <asp:ListItem>B</asp:ListItem>
          <asp:ListItem>C</asp:ListItem>
 </asp:CheckBoxList>

2. Add a CustomValidator Control from the toolbox.

I have added a ClientValidateFunction which will be a javascript function ValidateCheckBoxList  to validate.

<asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="Please select alt-east one option" ClientValidationFunction="ValidateCheckBoxList"></asp:CustomValidator>

3. Add a Button to Check the Validations are working.


 <asp:Button ID="Button1" runat="server" Text="Button" />


4. Add the following java script to the Page which will validate the CheckBoxList.

  <script type="text/javascript">
        function ValidateCheckBoxList(source, args) {
            var chkListModules = document.getElementById('<%= CheckBoxList1.ClientID %>');
            var chkListinputs = chkListModules.getElementsByTagName("input");
            for (var i = 0; i < chkListinputs.length; i++) {
                if (chkListinputs[i].checked) {
                    args.IsValid = true;
                    return;
                }
            }
            args.IsValid = false;
        }


    </script>

No comments:

Post a Comment