Quantcast
Channel: General .NET – Brian Pedersen's Sitecore and .NET Blog
Viewing all articles
Browse latest Browse all 167

Validate CheckBoxList using a CustomValidator

$
0
0

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.



Viewing all articles
Browse latest Browse all 167

Trending Articles