You could use a CustomValidator for this purpose. I've realized it in an old VB.NET project.
Here is the relevant aspx:
<asp:ListBox ID="LbSymptomCodesInsert" runat="server"
CausesValidation="true"
ValidationGroup="VG_RMA_SAVE" SelectionMode="Multiple">
</asp:ListBox>
<asp:CustomValidator ID="CV_SymptomCodeSelectionCount" runat="server"
ValidateEmptyText="true"
ClientValidationFunction="validateSymptomCodeSelectionCount"
OnServerValidate="validateSymptomCodeSelectionCount"
ControlToValidate="LbSymptomCodesInsert"
Display="None"
EnableClientScript="true"
ErrorMessage="Select at least one and at most 5 SymptomCodes"
Style="visibility: hidden"
ValidationGroup="VG_RMA_SAVE">*</asp:CustomValidator>
Here are the javascript functions:
function validateSymptomCodeSelectionCount(sender, args){
var listbox = document.getElementById('LbSymptomCodesInsert');
args.IsValid = validateListBoxSelectionCount(listbox, 1, 5);
}
function validateListBoxSelectionCount(listbox, minSelected, maxSelected){
var selected=0;
if(listbox != null){
for (var i=0; i<listbox.length; i++){
if(listbox.options[i].selected){
selected++;
if(selected>maxSelected)break;
}
}
}
return (selected >= minSelected && selected <= maxSelected);
}
Here's the ServerValidate (VB.NET but i'm sure you get the point):
Protected Sub validateSymptomCodeSelectionCount(ByVal source As Object, ByVal args As ServerValidateEventArgs)
Dim count = 0
For Each item As ListItem In LbSymptomCodesInsert.Items
If item.Selected Then count += 1
If count > 5 Then Exit For
Next
args.IsValid = (count >= 1 AndAlso count <= 5)
End Sub
Ncheckboxes and you want to only allow the user to checkN-Mcheckboxes, where you want to specifyMin code? I'd check this serverside and clientside, for the latter you'll need JavaScript.