Sunday, 22 January 2012

CheckBox List Validation in Asp.Net

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;
}
}

2 comments:

  1. Thank you, Thank you, I could not find this anywhere.

    ReplyDelete
  2. Yes, Thank You. This is powerful and simple.

    ReplyDelete