Home > Asp.net > Validating Checkboxlist using CustomValidator

Validating Checkboxlist using CustomValidator


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


About these ads
  1. No comments yet.
  1. No trackbacks yet.

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

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: