Feeds:
Posts
Comments

Archive for June, 2012

In my aspx page I have several CheckBoxList and the requirement is client side validation for all the CheckBoxList in the page before page submission.
As CheckListBox do not support Required Validator we need to user Custom Validator for this validation.

Here is the sample of my ASPX code

<div>
<asp:CheckBoxList runat=”server” ID=”chkList1″>
<asp:ListItem Text=”List Item 1_1″ Value=”11″></asp:ListItem>
<asp:ListItem Text=”List Item 1_2″ Value=”12″></asp:ListItem>
</asp:CheckBoxList>

<asp:CustomValidator ID=”validator_chkList1″ ClientValidationFunction=”ValidateCheckList” runat=”server”>*Select at least one item</asp:CustomValidator>

<asp:CheckBoxList runat=”server” ID=”chkList2″>
<asp:ListItem Text=”List Item 2_1″ Value=”21″></asp:ListItem>
<asp:ListItem Text=”Lsit Item 2_2″ Value=”22″></asp:ListItem>
</asp:CheckBoxList>
<asp:CustomValidator ID=”validator_chkList2″ ClientValidationFunction=”ValidateCheckList” runat=”server”>*Select at least one item</asp:CustomValidator>

<asp:Button runat=”server” ID=”btnSubmit” onclick=”btnSubmit_Click” />
</div>

&nbsp;

I used the following javascript to do the validation

function ValidateCheckList(sender, args) {
var chkControlId = sender.id.replace("validator_", "");
alert(chkControlId);
var options = document.getElementById(chkControlId).getElementsByTagName('input');
var ischecked = false;
args.IsValid = false;
for (i = 0; i < options.length; i++) {
var opt = options[i];
if (opt.type == "checkbox") {
if (opt.checked) {
ischecked = true;
args.IsValid = true;
}
}
}
}

Nice and easy trick but it took around two hours for me to figure out, that’s why sharing.
Happy coding. 🙂

Advertisements

Read Full Post »