3

How to apply textbox blank validation on button click inside gridview in javascript?I have a gridview that contains 2 textboxes and a save button in each row.I want to validate the textboxes on corresponding save button click.

I have applied the logic but problem is that it will only work for textBox ids that are hardcoded.How can I modify this code so that it will work for all the gridview rows?

function gvValidate() {

var grid = document.getElementById('<%= GridViewCTInformation.ClientID %>');
 if(grid!=null) 
  {
   var Inputs = grid.getElementsByTagName("input"); 
    for(i = 0; i < Inputs.length; i++) 
     {
      if(Inputs[i].type == 'text' ) 
       {
           if (Inputs[i].id == 'ctl00_contentPlaceHolderSubScreen_GridViewCTInformation_ctl02_TextBoxCTTermCode') 
             {
                 if (Inputs[i].value == "") {
                     alert("Enter values,blank is not allowed");
                     return false;
                 }

             }
             else if (Inputs[i].id == 'ctl00_contentPlaceHolderSubScreen_GridViewCTInformation_ctl02_TextBoxCTTermDesc') {
                 if (Inputs[i].value == "") {
                     alert("Enter values,blank is not allowed");
                     return false;
                 }
             }

      }
     }
     return true;
 }

}

 Protected Sub GridViewTaxInformation_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridViewTaxInformation.RowDataBound
    Try
        If e.Row.RowType = DataControlRowType.DataRow Then

            Dim btnSave As Button = DirectCast(e.Row.FindControl("ButtonSave"), Button)
            btnSave.Attributes.Add("onclick", "return gvValidate()")
        End If
    Catch ex As Exception
        Common.WriteLog(ex.Message)
        Common.WriteLog((ex.StackTrace))
        Response.Redirect("..\Errors.aspx", False)
    End Try
End Sub
3
  • what do you mean by for all the rows ? Commented May 11, 2012 at 7:19
  • Actually I have gridview in which on each row I have 2 textboxes and a save button.I want to validate that particular record whose save button is clicked. Commented May 11, 2012 at 7:24
  • why don't you use the validation control like : RequiredFieldValidator Commented May 11, 2012 at 7:35

4 Answers 4

2

Finally I got the solution of my problem..I have just passed index of row of gridview to javascript function.

Here's the code

 function gvValidate(rowIndex) {

var grid = document.getElementById('<%= GridViewCTInformation.ClientID %>');
 if(grid!=null) {
     var Inputs = grid.rows[rowIndex + 1].getElementsByTagName("input"); 
    for(i = 0; i < Inputs.length; i++) 
     {
      if(Inputs[i].type == 'text' ) 
       {
                  if (Inputs[i].value == "") {
                     alert("Enter values,blank is not allowed");
                     return false;
                 }

      }
     }
     return true;
 }

}

Protected Sub GridViewCTInformation_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridViewCTInformation.RowDataBound
    Try
        If e.Row.RowType = DataControlRowType.DataRow Then
            Dim btnSave As Button = DirectCast(e.Row.FindControl("ButtonCTInfoSave"), Button)
            btnSave.Attributes.Add("onclick", "return gvValidate(" + e.Row.RowIndex.ToString() + ")")
        End If
    Catch ex As Exception
        Common.WriteLog(ex.Message)
        Common.WriteLog((ex.StackTrace))
        Response.Redirect("..\Errors.aspx", False)
    End Try
End Sub
Sign up to request clarification or add additional context in comments.

1 Comment

If your answer is correct, accept it so future users will know.
1

Don't check for id. Simply check for blank value.

 if(Inputs[i].type == 'text' ) 
 {

             if (Inputs[i].value == "") {
                 alert("Enter values,blank is not allowed");
                 return false;
             }

  }

2 Comments

thanks for ur answer..But it will unnecessary check all the input controls,what if I want to validate only that textbox whose save button is clicked?
You can get the reference of the row from button object then check input box in that row. (I believe both are in the same row)If you post the output the html file that will help to understand the dom structure of the grid.
0
  <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="*" ControlToValidate="the name of your textbox to be validated" ForeColor="Red"></asp:RequiredFieldValidator>

try it may help u you may use the validation controls to validate any input

Comments

0
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
    $("[id*=GridView1] [id*=lnkUpdate]").click(function () {
        //Find the GridView Row using the LinkButton reference.
        var row = $(this).closest("tr");

        //Find the TextBox control.
        var txtName = row.find("[id*=txtName]");

        //Find the DropDownList control.
        var ddlCountries = row.find("[id*=ddlCountries]");

        var message = "";

        //Validate the TextBox control.
        if ($.trim(txtName.val()) == "") {
            message += "Please enter Name.\n";
        }

        //Validate the DropDownList control.
        if (ddlCountries.val() == "") {
            message += "Please select Country.";
        }

        //Display error message.
        if (message != "") {
            alert(message);
            return false;
        }
        return true;
    });
});
</script>

You may try above code for Grid View Validation.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.