Getting an ASP.NET CheckBoxList to work with a RequiredFieldValidator

I ran into a situation where I needed the System.Web.UI.WebControls.CheckBoxList to work with a System.Web.UI.WebControls.RequiredFieldValidator.

I found a clever and really easy way to fix it. I subclassed the CheckBoxList class to add the ValidationProperty that the RequiredFieldValidator is looking for.

Just declare this class:

[ValidationPropertyAttribute("ValidateableProperty")]
public class ValidateableCheckBoxList : CheckBoxList
{
    
    public string ValidateableProperty
    {
        get { return (this.Items.Cast<ListItem>()
            .Where(i => i.Selected).Count() > 0) ? 
            "something was selected" : ""; }
    }
}

And instead of using a CheckBoxList in your code, use a ValidateableCheckBoxList.

On the aspx file you can now work with the ValidateableCheckBoxList just like you would with a plain TextBox. I’m not a JavaScript guru so I did not implement or even thought about how to implement the client side validation.

        <ans:ValidateableCheckBoxList runat="server" 
            ID="testCheckBoxList">
            <asp:ListItem Text="asdf" />
            <asp:ListItem Text="asdf" />
            <asp:ListItem Text="asdf" />
        </ans:ValidateableCheckBoxList>
        <asp:RequiredFieldValidator runat="server" ID="rfvTest" 
            ControlToValidate="testCheckBoxList" Text="Failed validation"  />