In this article , I have explained how to validate
Asp.net checkboxlist using custom validator means I have to select atleast one
checkbox from checkboxlist.
Put the checkboxlist control on design page and
add some items in it and one cutome validator and one button.
<asp:CheckBoxList ID="CheckBoxList1"
runat="server">
<asp:ListItem Text="c#"></asp:ListItem>
<asp:ListItem Text="ASP"></asp:ListItem>
<asp:ListItem Text="Asp.Net"></asp:ListItem>
<asp:ListItem Text="Sql"></asp:ListItem>
<asp:ListItem Text="Ajax"></asp:ListItem>
</asp:CheckBoxList>
<asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="Please
select atleast one item from list." ForeColor="Red"
ClientValidationFunction="ValidateCheckBoxList"></asp:CustomValidator>
<asp:Button ID="Button1" runat="server" Text="Submit" />
JavaScript Function:-
Here I have written
javascript function for selecting atleast one checkbox from checkboxlist and
called this method on custom validator.
This function is executed
when cutom validator is trigered on button click.
If checkbox is checked then
isvalid value set to true else false.
<script type="text/javascript">
function ValidateCheckBoxList(sender,
args) {
var
checkBoxList=document.getElementById("<%=CheckBoxList1.ClientID
%>");
var
checkBox=document.getElementsByTagName("input");
var
isvalid=false;
for(var i=0;i<checkBox.length;i++)
{
if
(checkBox[i].checked) {
isvalid = true;
break;
}
}
args.IsValid = isvalid;
}
</script>
No comments:
Post a Comment
Note: only a member of this blog may post a comment.