Validate a CheckBoxList Ensuring At Least 1 Item is Choosen

Create your CheckBoxList and Validator but point the validator to a hidden textbox instead.

 <asp:CheckBoxList ID="CBMaterialItems" runat="server">
            <asp:ListItem Value="2009 Corporate Sustainability Report" />
            <asp:ListItem Value="2008 Annual Report & Financial Statement (Appendix A)" />
            <asp:ListItem Value="2008 Form 10-K (Includes Financial Statements for Operating Companies)" />
            <asp:ListItem Value="2007 Form 10-K (Includes Financial Statements for Operating Companies)" />
            <asp:ListItem Value="Most Recent Proxy Statement" />
            <asp:ListItem Value="Most Recent Form 10-Q" />
            <asp:ListItem Value="Most Recent Earnings Release" />
            <asp:ListItem Value="2007 Form 10-K (Includes Financial Statements for Operating Companies)" />
            <asp:ListItem Value="Dividend Reinvestment & Direct Stock Purchase Plan Application and Prospectus" />
        </asp:CheckBoxList>
        <asp:TextBox ID="cbMateralItemsValidator" value="." Style="display: none;" runat="server" />
        <cc1:CusVal ID="cusValMateralItems" runat="server" ErrorMessage="Please select the printed material you wish to receive"
            ControlToValidate="cbMateralItemsValidator" OnServerValidate="materialItemsValidator"
            CssClass="validator" Display="Dynamic">
        </cc1:CusVal>

Custom validator code

 protected void materialItemsValidator(object source, ServerValidateEventArgs args)
    {
        int counter = 0;

        for (int i = 0; i < CBMaterialItems.Items.Count; i++)
        {
            if (CBMaterialItems.Items[i].Selected)
            {
                counter++;
            }

            args.IsValid = (counter < 1) ? false : true;
        }
    }
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s