Validating a CheckBoxList with Javascript

Published on October 12, 2010 | Filed Under JavaScript

I was browsing some forums over the weekend and someone had asked how you can validate an ASP.NET CheckBoxList on the client-side. The natural instinct would be to use the RequiredFieldValidator control. Unfortunately, this control is not compatible with the CheckBoxList

The only way to properly accomplish this is by using Javascript, or creating a server-side user control that has some Javascript built into it. So here’s my solution:

<%@ Page Language="C#" AutoEventWireup="true"
  CodeFile="Default.aspx.cs" Inherits="Test_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
  <title>Checks Test</title>
  <script type="text/javascript">
    function ValidateChecks()
    {
      var ErrorMessage = document.getElementById('ErrorMessage');
      ErrorMessage.style.display = 'none';
      var groupName = 'lstChecks';
      var numChecks = 3;
      var numChecked = 0;
      var tmpCheck;
      for (var i = 0; i < numChecks; i++)
      {
        tmpCheck = document.getElementById(groupName + '_' + i);
        if (tmpCheck.checked)
          numChecked++;
      }
      if (numChecked == 0) {
        ErrorMessage.style.display = 'block';
        return false;
      }
      else
        return true;
    }
  </script>
</head>
<body>
  <form id="form1" runat="server">
  <div>
    <p>
      <asp:CheckBoxList ID="lstChecks" runat="server">
        <asp:ListItem Text="Yes" Value="1"></asp:ListItem>
        <asp:ListItem Text="Perhaps" Value="2"></asp:ListItem>
        <asp:ListItem Text="No" Value="3"></asp:ListItem>
      </asp:CheckBoxList>
    </p>
    <p id="ErrorMessage" style="display:none; color:#900;">
      You must select at least one!
    </p>
    <p>
      <asp:Button ID="btnSubmit" OnClientClick="return ValidateChecks();"
        Text="Submit" runat="server" />
    </p>
  </div>
  </form>
</body>
</html>

I believe it’s fairly straight-forward. The JavaScript code even has a place for you to insert the names of the items that you’ve used on the .NET side. But just in case, here’s a quick breakdown of my JavaScript code, for what I’ve done to accomplish this:

Variables

      var ErrorMessage = document.getElementById('ErrorMessage');
      ErrorMessage.style.display = 'none';
      var groupName = 'lstChecks';
      var numChecks = 3;
      var numChecked = 0;
      var tmpCheck;

Since we have this code in our head element, we’re forced to create a new variable for the ErrorMessage container. Right off the bat, make sure that you set the display property on this to none so that you don’t risk the message showing, when it’s not supposed to.

groupName is where you’ll store the name of your CheckBoxList at. You could hard-code the name throughout, but if something changes down the line and you need several lists on the page, this helps you to be able to expand upon your page. I’m a very big fan of planning for the “what if”!

The rest of your variables are pretty straight-forward

  • numChecks – Number of checkboxes to look for
  • numChecked – Current amount that are checked (this is called in the next step)
  • tmpCheck – Just a temporary variable to help us keep track of where we’re at in the list

Looping

      for (var i = 0; i < numChecks; i++)
      {
        tmpCheck = document.getElementById(groupName + '_' + i);
        if (tmpCheck.checked)
          numChecked++;
      }

Our tmpCheck object becomes the star in this block of code! Basically, you need to find each of the checkboxes and put them in tmpCheck to check if they are checked or not.

If you view the source of the current page, you will notice that the names of the checkboxes are lstChecks_0, lstChecks_1 and lstChecks_3. So there really is no other relationship between our checks, which is why it’s important to keep the group name as a variable.

If the current tmpCheck object is checked, we’re going to increase our numChecked integer.

Counting the Checks

      if (numChecked == 0) {
      	ErrorMessage.style.display = 'block';
        return false;
      }
      else
        return true;

For our final cleanup, we just have to count how many times we found a checked box. If we found 1 or more, we show our Error Message and return false (this is to stop the page refresh from happening). If we didn’t find any boxes checked, we just return true and go about our day.

Stopping Page Refreshes

I just spoke about returning false, if we found that some are checked. But just returning false doesn’t do anything. Take our button’s declaration into consideration:

      

Notice that our OnClientClick event uses the JavaScript function name, but uses the return keyword before it. This tells our button to look for a True or False value. If nothing is returned, it will just assumed that the value is True (although, it’s still better to return a value, regardless.)

What is OnClientClick?

In the world of JavaScript, onclick is what fires when someone clicks on the associated object. Unfortunately, ASP.NET uses the same keyword for their purposeses on the server side. This is where OnClientClick comes into play. On HTML, OnClick via ASP.NET will not render into anything, except for ASP.NET’s garbled code. If you want to display your own information, it will take OnClientClick and turn it into onclick within your HTML code.

Conclusion

I really hope this post has helped you to understand how to validate ASP.NET’s CheckBoxList without doing any programming within ASP.NET. You can definitely create a CustomValidator, but the amount of code that goes into it could turn out to be too much for someone who hasn’t had enough experience with it.

~Derek Torrence

Leave a Reply

*