You might be knowing that required field validator doesn't works with required field validator... so to accomplish that purpose we can use custom validator to validate checkbox list.
<asp:CheckBoxList ID="chkModuleList"runat="server" >
</asp:CheckBoxList>
1) Using ClientValidationFunction
<asp:CustomValidator runat="server" ID="cvmodulelist" ClientValidationFunction="ValidateModuleList" ErrorMessage="Please Select Atleast one Module" ></asp:CustomValidator>
function ValidateModuleList(source, args)
{
var chkListModules= document.getElementById ('<%= chkModuleList.ClientID %>');
var chkListinputs = chkListModules.getElementsByTagName("input");
for(var i=0;i<chkListinputs .length;i++)
{
if(chkListinputs [i].checked)
{
args.IsValid = true;
return;
}
}
args.IsValid = false;
}
2) Using OnServerValidate
<asp:CustomValidator runat="server" ID="cvmodulelist" OnServerValidate="ValidateModuleList" ErrorMessage="Please Select Atleast one Module" ></asp:CustomValidator>
private void ValidateModuleList(object sender, ServerValidateEventArgs e)
{
int cnt= 0;
for(int i=0;i<chkModuleList.Items.Count;i++)
{
if(chkModuleList.Items[i].Selected)
{
cnt++;
}
e.IsValid = (cnt== 0) ? false : true;
}
}
11 comments:
Thank you so much for this example... that help me a lot.
Thanks. I think the method needs to be public, if it is in code behind
it doesn't work for me :-(
Sorry, in response to the last comment "it doesn't work for me :-)".. This works fine. I forgot to give ValidationGroup.
Thanks Pankaj ! That was a lifesaver !
I got this error...
Compiler Error Message: CS0103: The name 'cbl_Purpose' does not exist in the current context
For ... var chkList = document.getElementById('<%= cbl_Purpose.ClientID %>');
** My checkboxlist id is cbl_Purpose
I got the same error as CMM. I believe it's because my checkboxlist is dynamically created based on the user's selection of another control.
Is there any way around this problem?
It works for checking. But the error remains as it is even after the checkboxes are selected.
Can anyone help with that. My email id is jainjayesh_2000@yahoo.com
After googling lots of site..
find perfect solution here.
10 on 10
Thanks! It helped me a lot! :)
Hi,
This is very informative article. Thanks for sharing your knowledge. There are few links that also helpful for developers. This article have described to validate CheckBox, CheckBoxList, DropDownList, FileUpload, RadioButton, RadioButtonList, TextBox using jquery.
http://mindstick.com/Articles/c3825daa-a449-467d-9513-34a8232d498a/?Validations%20on%20Asp%20Net%20Control
http://www.aspdotnet-suresh.com/2012/09/jquery-validate-checkboxlist-in-aspnet.html
Post a Comment