Validate CheckBoxList using a CustomValidator

In this article I explain how you can validate that at least one checkbox is checked in an asp:CheckBoxList using an asp:CustomValidator, and how to make it work server side and client side.

None of the built in .net validators will validate the asp:CheckBoxList, so you will have to create your own. If you are too lazy or in too big a hurry to create your own validation control, you can quickly whiff up a validation scenario using an asp:CustomValidator.

SETUP THE LIST AND THE VALIDATOR:

First the CheckBoxList:

<asp:CheckBoxList
  ID="cblInquiry"
  RepeatLayout="Flow"
  DataSource="<%# SomeDataSource %>"
  DataTextField="SomeField"
  DataValueField="SomeField">
  runat="server"
</asp:CheckBoxList>

Then add the CustomValidator:

<asp:CustomValidator
  OnServerValidate="valInquiry_ServerValidation"
  ID="valInquiry"
  EnableClientScript="true"
  ClientValidationFunction="verifyCheckboxList"
  ErrorMessage="Some error message"
  runat="server"
</asp:CustomValidator>

Do NOT set the ControlToValidate property on the asp:CustomValidator. If you do you will get the following error:

Validation Error

APPLY SERVER SIDE VALIDATION:

The CustomValidator has a code-behind function called valInquiry_ServerValidation. this function is quite simple:

protected void valInquiry_ServerValidation(object source, ServerValidateEventArgs args)
{
  args.IsValid = cblInquiry.SelectedItem != null;
}

The custom validator will now execute the validation on server side. Use the Page.IsValid to ensure that all validations are successfull.

APPLY CLIENT-SIDE VALIDATION:

The CustomValidator has also a client-side JavaScript referenced in the ClientValidationFunction property. This JavaScript looks like this:

<script type="text/javascript" language="javascript">
  function verifyCheckboxList(source, arguments) {
    var val = document.getElementById("<%# cblInquiry.ClientID %>");
    var col = val.getElementsByTagName("*");
    if (col != null) {
      for (i = 0; i < col.length; i++) {
        if (col.item(i).tagName == "INPUT") {
          if (col.item(i).checked) {
            arguments.IsValid = true;
            return;
          }
        }
      }
    }
    arguments.IsValid = false;
  }
</script>

Please also note that since the ControlToValidate property cannot be used on a CheckBoxList you need to hard-select the clientID of the CheckBoxList in the JavaScript.

You will need to do a DataBind() on Page_Load() in order for the <%# cblInquiry.ClientID %> to be databound.

That’s it. Happy coding.

About briancaos

Developer at Pentia A/S since 2003. Have developed Web Applications using Sitecore Since Sitecore 4.1.
This entry was posted in .net, c#, General .NET and tagged , , , , , , , , . Bookmark the permalink.

6 Responses to Validate CheckBoxList using a CustomValidator

  1. Pingback: cmsnewstoday.com is stealing my content? | Brian Pedersen's Sitecore and .NET Blog

  2. Mike Wootten says:

    Hi Brian,

    Cool code, but I’m having problems with the last bit. I’m new to C# and was wondering if you could give an example of how you would hard-select the clientID. The CheckBoxlist data is already databound in the page_load event.

    Cheers

    Like

  3. vikas says:

    HI Mr.Briancaos
    I have Executed this code on Server side It’s working very well.
    thanks sir.

    Like

  4. Felipe Titonel says:

    Função mais simples:
    function ValidaCheckBoxTemas(sender, args)
    {
    args.IsValid = false;
    var countChecked = $(‘# :checkbox:checked’).length;
    if (countChecked > 0) {
    args.IsValid = true;
    }
    }

    Like

  5. Pingback: Useful Links for .NET Programmer | Arnold Sia's space

  6. Asif says:

    since, I am not adding ControlToValidate property, I am not able to cast “source” as CheckBoxList in valInquiry_ServerValidation.

    Like

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.