** You can read also this newer post about Writing a reusable CheckBoxValidator. **
Here we go again with the CustomValidator.
This time we will try to validate a maximum number of checkboxes selected in the page.
Let's start with a CheckBoxList and a submit button on our page.
<asp:CheckBoxList runat="server" ID="ChexkBoxList" />
<asp:CustomValidator
runat="server"
ID="MyCustomValidator"
OnServerValidate="MyCustomValidator_ServerValidate"
ErrorMessage="Select max 2"
/>
<asp:Button runat="server" Text="Submit" />
We will populate the CheckBoxList on page load with a simple string array.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string[] values = new string[] { "CheckBox 1", "CheckBox 2", "CheckBox 3" };
ChexkBoxList.DataSource = values;
ChexkBoxList.DataBind();
}
}
Now we are going to add our server-side custm validation (a must!).
protected void MyCustomValidator_ServerValidate(
object source, ServerValidateEventArgs args)
{
int count = 0;
foreach (ListItem item
in ChexkBoxList.Items)
if (item.Selected)
count++;
args.IsValid = count <= 2;
}
This will loop through the items of the CheckBoxList and count the selected ones.
The validation is successful if the selected items count is not greater than the desired value.
Our server-side validation is complete.
Let's add a client-side validation logic (nice-to-have).
We need a javascript function that will keep count of the selected checkboxes on the client, and will store that value in a HiddenField:
<asp:HiddenField runat="server" ID="SelectedCheckBoxesCount" Value="0" />
<script type=
"text/javascript">
function onCheckBoxCheck(item) {
var selectedCheckBoxesCount = document.getElementById(
'<%= SelectedCheckBoxesCount.ClientID %>');
var count = Number(selectedCheckBoxesCount.value);
if (item.
checked)
count += 1;
else count -= 1;
selectedCheckBoxesCount.value = count;
}
</script>
This function needs to be called on each checkbox click, so we need to add the handler to each item in the CheckBoxList.
This must be done after binding the datasource to the list.
Here is the new page load event handler.
protected void Page_Load(
object sender, EventArgs e)
{
if (!IsPostBack)
{
string[] values =
new string[] {
"CheckBox 1",
"CheckBox 2",
"CheckBox 3" };
ChexkBoxList.DataSource = values;
ChexkBoxList.DataBind();
foreach (ListItem item in ChexkBoxList.Items)
item.Attributes["onclick"] = "onCheckBoxCheck(this)";
}
}
One more step, create the client-side validation function and bind it to the custom validator.
It will verify the hiddenfield's value and validate it if it is less or equal to the desired value.
<script type=
"text/javascript">
function checkBoxListValidation(sender, args) {
var selectedCheckBoxesCount = document.getElementById(
'<%= SelectedCheckBoxesCount.ClientID %>');
var count = Number(selectedCheckBoxesCount.value);
args.IsValid = count <= 2;
}
</script>
<asp:CustomValidator
runat="server"
ID="MyCustomValidator"
OnServerValidate="MyCustomValidator_ServerValidate"
ErrorMessage="Select max 2"
ClientValidationFunction="checkBoxListValidation"
/>
Good, we are done!
Obviously we can use this mechanism to validate for any number of selected checkboxes, for a minimum amount, or even for a range (select at least two, but maximum 4).