Checkboxlist Validation in Asp.Net

In this post, I would like to illustrate a simple requirement of Checkboxlist Validation. It is a common requirement to validate if a user has selected at least one item from available choice of items in an Asp Checkboxlist Control. Although, there are ways using Javascript etc. but I like to keep a strict control so this solution uses a Asp Custom Validator Control.

Here is a Checkboxlist; for sake of simplicity I have bound this to a DataSource, you can bind to either a datasource or a static set of options.


<asp:CheckBoxList ID="cblChoices" DataValueField="ChoiceID" DataTextField="Title" RepeatDirection="Horizontal" RepeatColumns="2" RepeatLayout="Table" CellPadding="1" CellSpacing="5" runat="server" />

Now, add a Custom Validator Control that works in conjunction with the above.


<asp:CustomValidator ID="CheckboxChoiceRequiredValidator" runat="server" ErrorMessage="Please opt in by selecting at least one choice" ValidationGroup="MyValGroup" Font-Bold="true" ForeColor="Red" OnServerValidate="CheckboxChoiceRequiredValidator_ServerValidate">

In the above, the most important attribute is OnServerValidate which listens to a method CheckboxChoiceRequiredValidator_ServerValidate which you need to have in the code behind. Lets, add the method in the code behind. [C# example; Use Tools to get Telerik Code Convertor for VB]

protected void CheckboxChoiceRequiredValidator_ServerValidate(object source, ServerValidateEventArgs args)

{

int cnt = 0;

for (int i = 0;i < cblChoices.Items.Count; i++)

{

if (cblChoices.Items[i].Selected) { cnt++; }

}

if (cnt == 0)

{

args.IsValid = false;

}

else

{

args.IsValid = true;

}

}

In the method above, a simple iteration to find out if there are selections made by user, and returning args as Boolean. Here I am using the if (cnt == 0) to check against zero but you can check for example (2) to ensure user have selected at least two choices. The main thing is of course, that Button Click event that checks for Checkboxlist Validation needs to have (see below) To ensure the Checkboxlist Validation is fired everytime a Button is clicked.

If (page.isValid) { }

Hope this was helpful.

Advertisements

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