Client Side Validation Of GridView with JavaScript.
Many people are asking me how to validate GridView with JavaScript. How to get control client Id on client side. This article and attached code snippet shows you to create a validate method in JavaScript and call it from your ASP.NET page's code behind to validate the controls.
In my sample example, I have taken on GridView with checkbox and TextBox in the gridview. Just copy this code in your aspx page. As you can see in the below code, I have a validate method. Thid methods finds each control in a GridView row using getElementById as an object and then checks if it is checked or not and so on.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<script type="text/javascript">
function validate()
{
for(j=0;j<grd_Cb.length;j++)
{
var obj = document.getElementById(grd_Cb[j]);
if(obj.checked ==true)
{
Checkbol=1;
bool=1;
}
}
if(bool==0)
{
alert(" Please enter atleast one Passenger");
return false;
}
if (Checkbol==1)
{
for(i=0;i<grd_Cb.length;i++)
{
var Obj1 = document.getElementById(grd_Cb[i]);
if(Obj1.checked ==true)
{
var objFirstName=document.getElementById(grdFirstName_Txt[i]);
if(objFirstName.value=="")
{
alert("Line No : "+ [parseInt(i)+1]+ " First name can not be blank");
objFirstName.focus();
return false;
}
var objLastName=document.getElementById(grdLastName_Txt[i]);
if(objLastName.value=="")
{
alert("Line No : "+ [parseInt(i)+1]+ " Last name can not be blank");
objLastName.focus();
return false;
}
}
}
}
return true;
}
</script>
<title>JavaScript Validation on Grid</title>
</head>
<body>
<form id="form1" runat="server">
<asp:GridView runat="server" ID="JavascriptGrid" AutoGenerateColumns="False" Width="100%" OnPreRender="JavascriptGrid_PreRender">
<Columns>
<asp:TemplateField HeaderText="Validate">
<ItemTemplate>
<asp:CheckBox CssClass="textbox" runat="server" ID="ChkValidate" />
</ItemTemplate>
<ItemStyle Width="10px" />
</asp:TemplateField>
<asp:TemplateField HeaderText="First Name">
<ItemTemplate>
<asp:TextBox ID="FirstName" Text='<%#Eval("FirstName") %>' runat="server" Width="140"></asp:TextBox>

Dharmendra KumarPosted Sep 14, 2015, 1:45 AM
working great, Thanks a lot
Joss PeroldPosted Nov 20, 2012, 6:24 AM
hi I know this is an old post, but i am new to javascript. I was wondering if it is possible to do this after post like at a button click that then runs the gridview databound event. I cant seem to add an array at this point.
Milind BiloniaPosted Jul 16, 2012, 7:30 AM
It a very good resources...!! Killer Code..!! Thanks for Share...!!
nidhi guptaPosted Apr 26, 2012, 12:56 AM
Very useful example for a beginner like me. Thanks Vishal.
milind babarPosted Mar 1, 2011, 5:37 AM
good