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"  />
Advertisements

5 thoughts on “Getting an ASP.NET CheckBoxList to work with a RequiredFieldValidator

    • Bahre, I think you’re forgetting to register the custom control. You need something similar to this at the top of the aspx page.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s