Easily Validate ASP.NET CheckBoxLists With jQuery

by Shawn Duggan on 03/08/2009

The CheckBoxList control is very handy and easy to use.  Unfortunately when it comes to validating it, none of the built in ASP.NET validators can get the job done.  If you need to make sure the user has selected at least one of the checkboxes in the list, adding a RequiredFieldValidator will throw a runtime exception informing you that the CheckBoxList cannot be validated.

Most of the solutions found involved creating your own custom validator that inherited from BaseValidator.  I didn’t try any of them; I guess they work, but it just felt like too much work.  Thankfully there is a much simpler way.

jQuery is the Swiss Army knife of client side scripting.  The more I use it, the better I like it.  Here’s how to use jQuery to solve the same problem in less than 5 minutes.  Please note the code samples here have been modified from a DotNetNuke module I am currently writing.

First, let’s create our CheckBoxList and assign a class that we will use later in a jQuery selector:

   1: <asp:CheckBoxList id="cblEvents" runat="server" RepeatDirection="Horizontal" CssClass="CheckBoxList">
   2:   <asp:ListItem Text="Apples" Value="Apples"></asp:ListItem>
   3:   <asp:ListItem Text="Oranges" Value="Oranges"></asp:ListItem>
   4:   <asp:ListItem Text="Mangoes" Value="Mangoes"></asp:ListItem>
   5: </asp:CheckBoxList>

It would be nicer if we could assign the class directly to the ListItem, but we can’t.  The rendered markup of this control would be something like:

   1: <table id="dnn_ctr370_ViewModuleName_cblEvents" class="CheckBoxList" border="0">
   2:     <tr>
   3:         <td><input id="dnn_ctr370_ViewModuleName_cblEvents_0" type="checkbox" name="dnn$ctr370$ViewModuleName$cblEvents$0" />
   4:             <label for="dnn_ctr370_ViewModuleName_cblEvents_0">Apples</label></td>
   5:         <td><input id="dnn_ctr370_ViewModuleName_cblEvents_1" type="checkbox" name="dnn$ctr370$ViewModuleName$cblEvents$1" />
   6:             <label for="dnn_ctr370_ViewModuleName_cblEvents_1">Oranges</label></td>
   7:         <td><input id="dnn_ctr370_ViewModuleName_cblEvents_2" type="checkbox" name="dnn$ctr370$ViewModuleName$cblEvents$2" />
   8:             <label for="dnn_ctr370_ViewModuleName_cblEvents_2">Mangoes</label></td>
   9:     </tr>
  10: </table>

Notice how the CheckBoxList is actually rendered as a table and that its id has been altered, but the class name is intact.  ASP.NET renames child controls so they are unique.  This why we added the class to our CheckBoxList.  We are going to use the class in a jQuery selector to find the table, and then pull out all the child checkbox controls.

Next, create a CustomerValidator that we will use to call our custom client side jQuery validation function:

   1: <asp:CustomValidator id="cvEventsValidator" Display="Dynamic" ValidationGroup="Submit" runat="server"
   2:       ClientValidationFunction="ValidateCheckBoxList">&nbsp;required</asp:CustomValidator>

The final piece is to write our jQuery validation function.  Here it is:

   1: function ValidateCheckBoxList(sender, args) {
   2:     args.IsValid = false;
   3:
   4:     jQuery(".CheckBoxList").find(":checkbox").each(function() {
   5:         if (jQuery(this).attr("checked")) {
   6:             args.IsValid = true;
   7:             return;
   8:         }
   9:     });
  10: }

The selector above first finds all the elements with the class “CheckBoxList”, and within that matched set finds all the child elements of type “checkbox”, and for each of those checks to see if it is checked.  It returns true as soon as it finds a checkbox that has been checked.  I probably could have also used a selector like jQuery(“select[id$=cblEvents]”) for the same purpose (targeting controls whose id ends with cblEvents).

  • Print
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • Add to favorites
  • RSS
  • StumbleUpon
  • Twitter
  • Tumblr
  • email
  • LinkedIn
  • Netvibes
  • Posterous
  • Suggest to Techmeme via Twitter
  • Technorati

{ 9 comments… read them below or add one }

1 roberto July 5, 2009 at 2:06 am

Is possible in Asp.NET generate a checkbox with ID and NAME attribute different?

2 Matt July 28, 2009 at 1:01 pm

Seems great, but for some reason it’s not forcing validation. I’m using it in a wizard step. Is there a good way to set a validation group for a “Continue” button in a wizard? I don’t think I want the same validation group set for ALL of the “Continue” buttons, do I? Maybe that’s my problem?

3 Zashkaser August 5, 2009 at 12:44 pm

The best information i have found exactly here. Keep going Thank you

4 sandra407 September 9, 2009 at 12:07 pm

Hi! I was surfing and found your blog post… nice! I love your blog. :) Cheers! Sandra. R.

5 hotyuew October 20, 2009 at 5:33 pm

И вот долгожданный топик от автора, спасибо как всегда на высоте!

6 Zed November 9, 2009 at 8:59 am

वाह !

7 PGN March 26, 2010 at 6:01 am

Simply the best

8 Juan March 26, 2010 at 9:47 am

It turns out there is an undocumented “feature” of the ListItem class where you can assign an onclick client side event and it works!

My Selection

Intellisense does not support this property but the class does. It renders the appropriate JavaScript client side event.

9 celebrity fuck you August 24, 2010 at 2:34 pm

Sign: zdbrw Hello!!! thybd and 3702whsfngsamg and 1336 : I like your blog. cool post!

Leave a Comment

Previous post:

Next post: