Ahmed Farouk
Ahmed Farouk

Reputation: 21

Validate TextBoxes By CustomValidators in Gridview jquery

Simply I have a Gridview has two ItemTemplate one for a TextBox and other for a CustomValidator and i have a button outside this grid

the senario simply i want to valid the Textboxes by CustomValidators in the grid when i click the button

all i want that to catch the Textbox that found in the same row of the CustomValidator

in this function

function ValidateModuleList(source, args) {

}

I tried something like

function ValidateModuleList(source, args) {
    var row = $(this).parent('td').parent('tr');
    var textbox = row.find('textbox1') ;
}

but it doesn't work.

Validator:

<ItemTemplate>
     <asp:CustomValidator runat="server" ID="cvmodulelist" ClientValidationFunction="ValidateModuleList" CssClass="CustomValid" ErrorMessage="*" ValidationGroup="vg_Save_Req_TP_Settings">*
    </asp:CustomValidator> 
</ItemTemplate> 

Upvotes: 0

Views: 1334

Answers (1)

afzalulh
afzalulh

Reputation: 7943

In the CustomValidator set controlToValidate = "TextBox1". Templates may look like:

<asp:TemplateField >
        <ItemTemplate>
            <asp:TextBox ID="TextBox1" runat="server" CausesValidation="true" >
            </asp:TextBox>
        </ItemTemplate>
    </asp:TemplateField>
<asp:TemplateField >
    <ItemTemplate>
        <asp:CustomValidator runat="server" ID="cvmodulelist" ClientValidationFunction="ValidateModuleList" 
                            CssClass="CustomValid" ErrorMessage="*" 
                            ControlToValidate="TextBox1" 
                            ValidationGroup="vg_Save_Req_TP_Settings">*
        </asp:CustomValidator> 
    </ItemTemplate> 
</asp:TemplateField>

In script find the closest 'tr' of source. Find the textbox by part of it's name. Remember, server would render the textbox as something like <input name="GridView1$ctl03$TextBox1" type="text" id="GridView1_TextBox1_1" />. Here's the script you can use for test:

<script type="text/javascript">
    function ValidateModuleList(source, args) {
        var textbox = $(source).closest('tr').find('input[name*="TextBox1"]');
        alert(textbox.val());
    }
</script>

And don't forget to add a reference to jquery at the head of your page:

<head runat="server">
    <script src="Scripts/jquery-1.8.2.js"></script>  

Hope this will help you to start!

Upvotes: 1

Related Questions