15 March 2014

Client side validate checkboxlist using custom validator in Asp .Net



        In this article we will see how to validate checkboxlist at client side to make sure that at least one item is checked. To do this we will use custom validator control and javascript. 

Java script

<script type="text/javascript">
    function ValidatenumberList(source, args) {
        var chkListModules = document.getElementById('<%= cbl_number.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>


asp.net code:
<asp:checkboxlist id="cbl_number" runat="server">
<asp:listitem text="1" value="1"></asp:listitem>
<asp:listitem text="2" value="2"></asp:listitem>
<asp:listitem text="3" value="3"></asp:listitem>
<asp:listitem text="4" value="4"></asp:listitem>
<asp:listitem text="5" value="5"></asp:listitem>
<asp:listitem text="6" value="6"></asp:listitem>
<asp:listitem text="7" value="7"></asp:listitem>
</asp:checkboxlist>

<asp:customvalidator runat="server" forecolor="Red" id="Customvalidator1" clientvalidationfunction="ValidatenumberList" errormessage="Please select atleast one number."></asp:customvalidator>

<asp:button text="Select Number" id="btnTest" runat="server"></asp:button>

No comments:

Post a Comment