Validating a List of Checkboxes Image

Validating a List of Checkboxes

December 22, 2014      .net Programming

There are many times in a UI when the user is presented with a multiple choice list. Of course, the CheckBoxList is the go-to control in the scenario. Often times though, business logic dictates that at least one item in the list be selected. And this is where the CheckBoxList control falls short - Microsoft did not included a validator of any sort for it.

Use the code below to create your own custom server control that will force the use to select at least one item. This uses client-side logic and assumes that unobtrusive validation is enabled in your application.

[ToolboxData("<{0}:CheckBoxListValidator runat=server></{0}:CheckBoxListValidator>")]
public class CheckBoxListValidator : CustomValidator
{  
   /// <summary> 
   /// Constructs a new Email validator control
   /// </summary> 
   public CheckBoxListValidator() 
   {
      this.EnableClientScript = true;
      this.ClientValidationFunction = "validateCBL";
      this.ViewStateMode = System.Web.UI.ViewStateMode.Disabled;
      this.Display = ValidatorDisplay.Dynamic;
   }

   protected override void OnPreRender(EventArgs e)
   {
      base.OnPreRender(e);
      StringBuilder sbScript = new StringBuilder();
      sbScript.Append("function validateCBL(source, args) {");
      sbScript.Append("var id = $(source).attr('data-val-controltovalidate');args.IsValid = ($('#' + id + ' input:checked').length) > 0;");
      sbScript.Append("}");
      Page.ClientScript.RegisterStartupScript(this.GetType(), "BS_CBL_Vld", sbScript.ToString(), true);
   }

   protected override bool ControlPropertiesValid()
   {
      Control ctrl = FindControl(ControlToValidate);
      if (ctrl == null) 
         return false;
      if (!(ctrl is ListControl))
         return false; return true;
   }

   protected override bool OnServerValidate(string value)
   {
      if (!base.OnServerValidate(value))
         return false;
      return true;
   }
}

Notes:

  • I disable ViewState on this control as it is not needed at all.
  • The call to Page.ClientScript.RegisterStartupScript will register, and thus render, the client-side validation function only once if there are multiple instances of the validator on the same page.
  • The actual client-side test itself is a simply jQuery call that finds all input elements beneath the CheckBoxList's outer-most element's ID that are checked and counts the number of checked ones.
Share It