Thursday, February 11, 2010

Using Custom Validator for validating GridView

JS function---

 function ValidateGrid(source, args) {
            var cnt = 0;
            //Get target base & child control.
            var TargetBaseControl = document.getElementById('ctl00_ContentPlaceHolder1_GdUsers');
            var TargetChildControl = "ChkSel";

            //Get all the control of the type INPUT in the base control.
            var Inputs = TargetBaseControl.getElementsByTagName("input");

            //Checked/Unchecked all the checkBoxes inside the GridView.
            for (var n = 0; n < Inputs.length; ++n) {
                if (Inputs[n].type == 'checkbox' && Inputs[n].id.indexOf(TargetChildControl, 0) >= 0) {
                    if (Inputs[n].checked == true)
                        cnt += 1;
                }
            }
            if (cnt > 0) {
                args.IsValid = true;
            }
            else {
                args.IsValid = false;
            }
        }

Button which causes validation--

 <asp:ImageButton ID="cmdDelete" runat="server" ValidationGroup="Val1"
                                runat="server" Text="Delete" OnClick="BtnDelete_Click" CssClass="a"
                                Height="37px" ImageUrl="~/Images/Delete.gif" Width="118px" />

CustomValidator--

<asp:CustomValidator ID="CusVal1" runat="server" Display="Dynamic" ClientValidationFunction="ValidateGrid" ControlToValidate="cmdDelete"
                    ErrorMessage="Select any user/users!"></asp:CustomValidator>

No comments:

Post a Comment