Click here to Skip to main content
14,236,939 members

ASP.NET GridView Client Side Validation

Rate this:
5.00 (4 votes)
Please Sign up or sign in to vote.
5.00 (4 votes)
30 Jul 2014CPOL
We will explore the technique in jQuery to validate the ASP.NET GridView.


Email Validation Failed Alert

We will explore the technique in jQuery to validate the ASP.NET GridView.

Setting up the GridView First

On aspx Page

We will show following fields in GridView.

  • Name – TextBox
  • Age – TextBox
  • Email – TextBox
  • Date of Birth – TextBox (with jQuery DatePicker)
  • Gender – RadioButtonList

For each field, we will have one TemplateField with

  1. ItemTemplate (shows when Grid is loaded) – Inside this, a Label to show the value.
  2. EditItemTemplate (shows when Grid is in Edit Mode) – Inside this, actual TextBox or RadioButtonList.
<asp:GridView ID="gvTestValidations" runat="server" AutoGenerateColumns="false" OnRowEditing="gvTestValidations_RowEditing"
	OnRowUpdating="gvTestValidations_RowUpdating" OnRowCancelingEdit="gvTestValidations_RowCancelingEdit">
		<asp:TemplateField HeaderText="Name">
				<asp:Label ID="lblName" runat="server" Text='<%#Bind("Name") %>'></asp:Label>
				<asp:TextBox ID="txtName" runat="server" Text='<%#Bind("Name") %>' />
		<asp:TemplateField HeaderText="Age">
				<asp:Label ID="lblAge" runat="server" Text='<%#Bind("Age") %>'></asp:Label>
				<asp:TextBox ID="txtAge" runat="server" Text='<%#Bind("Age") %>' />
		<asp:TemplateField HeaderText="Email">
				<asp:Label ID="lblEmail" runat="server" Text='<%#Bind("Email") %>'></asp:Label>
				<asp:TextBox ID="txtEmail" runat="server" Text='<%#Bind("Email") %>' />
		<asp:TemplateField HeaderText="Date Of Birth">
				<asp:Label ID="lblDOB" runat="server" Text='<%#Bind("DOB") %>'></asp:Label>
				<asp:TextBox ID="txtDOB" runat="server" Text='<%#Bind("DOB") %>' />
		<asp:TemplateField HeaderText="Gender">
				<asp:Label ID="lblGender" runat="server" Text='<%#Bind("Gender") %>'></asp:Label>
				<asp:RadioButtonList ID="rblGender" runat="server" SelectedValue='<%#Bind("Gender") %>'>
					<asp:ListItem Value="Male">Male</asp:ListItem>
					<asp:ListItem Value="Female">Female</asp:ListItem>
		<asp:CommandField ShowEditButton="true" HeaderText="Edit" />

On aspx.cs Page

As I am not using Database, so to bind the GridView, we can have one DataTable property stored in ViewState. We will edit, update to the ViewState Table and bind that to the GridView. Inside the Page Load, we will declare hard-coded rows and add them to DataTable. Then bind that to the Grid.

// This ViewState DataTable Property holds the GridView Data.
DataTable dtGridData
        return (DataTable)ViewState["dtGridData"];
        ViewState["dtGridData"] = value;

protected void Page_Load(object sender, EventArgs e)
	if (!IsPostBack)
		// Add Column for the DataTable.
		DataTable dt = new DataTable();
		dt.Columns.Add(new DataColumn("Name"));
		dt.Columns.Add(new DataColumn("Age"));
		dt.Columns.Add(new DataColumn("Email"));
		dt.Columns.Add(new DataColumn("DOB"));
		dt.Columns.Add(new DataColumn("Gender"));

		// Add Rows to DataTable.
		DataRow dr = dt.NewRow();
		dr["Name"] = "Deepak Mahapatra";
		dr["Age"] = 24;
		dr["Email"] = "";
		dr["DOB"] = "09/28/1990";
		dr["Gender"] = "Male";


		dr = dt.NewRow();
		dr["Name"] = "Dillip Das";
		dr["Age"] = 24;
		dr["Email"] = "";
		dr["DOB"] = "10/02/1990";
		dr["Gender"] = "Male";


		dr = dt.NewRow();
		dr["Name"] = "Tadit Dash";
		dr["Age"] = 24;
		dr["Email"] = "";
		dr["DOB"] = "07/05/1990";
		dr["Gender"] = "Male";


		// Assign the DataTable to dtGridData, so that it is stored in ViewState.
		// After that, bind the GridView.
		dtGridData = dt;

private void BindGrid()
	gvTestValidations.DataSource = ViewState["dtGridData"];

What’s on Browser?

Initial Load

GridView on Browser

On Row Edit Button Click

First Row in Edit Mode

Now, the Actual Show Begins !!!

We will do following validation…

  • For Age Field – Only Allow Numbers
  • For Email Field – Email Validation

You can do more validations, you just need to learn how to do it.

So, How to?

Logic is that, inside the document Ready Event, we will try to find all the Age TextBoxes and Email TextBoxes inside the GridView and handle the keydown and change events respectively.

For Age TextBox

The highlighted code lines are important.

$("#gvTestValidations tr input[id*='txtAge']").each(function () {
	$(this).keydown(function (event) {
        // Just to find all non-decimal characters and replace them with blank.
		$(this).val($(this).val().replace(/[^\d].+/, ""));

		var charCode = (event.which) ? event.which : event.keyCode;
		if (charCode > 31 && (charCode < 48 || charCode > 57)) {

			isValidated = false;
		else { isValidated = true; }

The first important line is…

$("#gvTestValidations tr input[id*='txtAge']")

This is actually searching for all the TextBoxes inside the Grid with the help of Attribute Contains Selector [name*="value"].
Then the following code attaches the keydown Event with all those matched Age TextBoxes.

$(this).keydown(function (event) {
    // Validation code here...

For Email TextBox

The same logic is used for Email TextBox. The only difference is that we are handling the change Event here instead of keydown Event.

$("#gvTestValidations tr input[id*='txtEmail']").each(function () {
	$(this).change(function (event) {
		if (!validateEmail($(this).val())) {
			alert("Email not in correct format.");

			isValidated = false;
		else {

			isValidated = true;

NOTE: The CSS class “errorClass” is used to make Email TextBox Border Red-Coloured, when validation fails.

One more interesting thing…

We are also restricting User to Update one record, if the row is not validated. Suppose, User has typed one wrong Email Id and then directly hits the Update Button, so it won’t allow the User to Update and show one message. For that, we are using the variable isValidated, which you have already seen inside the code.
We are just checking the isValidated value inside the Update Button click and taking action according to that. Again the same logic, which is searching all the links and finds the Button, which is having Text as “Update” and fires its click Event.

$("#gvTestValidations a").each(function () {
	if ($(this).text() == "Update") {
		$(this).click(function (event) {
			if (!isValidated) {
				alert("There are issues with input fields. Please correct and then try.");
				return false;
			else { return true; }

Update Button not working if Validation Fails

Thanks !!!

For taking time and reading the Blog. Download the Project and play with it. If you find it useful, then share within your circle, by pressing the Social Icons.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Tadit Dash (ତଡିତ୍ କୁମାର ଦାଶ)
Software Developer Mindfire Solutions
India India
Official Facebook Page - Tadit Dash

Proud Indian | Microsoft MVP | CodeProject MVP | Speaker | Author | DZone Most Valuable Blogger | Community Expert | Moderator | jsfiddler | Cook | Dancer

Currently working @Mindfire Solutions.
Love to code and help guys to Trap the Bug.

My Tech Blog

Programming Community Profiles

jsfiddle | Stack Overflow

Other Blog Profiles

Mindfire CRM Team Blog | Mindfire Blog

Social Profiles

Facebook | Twitter | LinkedIn | Google+


  1. DZone Most Valuable Blogger
  2. Microsoft MVP 2014, 2015, 2016
  3. Code Project MVP 2014, 2015, 2016
  4. Star Achiever of the Month December 2013
  5. Mindfire Techno Idea Contest 2013 Winner
  6. Star of the Month July 2013
  7. </

Comments and Discussions

Questioncode to allow int and float value in a textbox Pin
Pongavanam18-Jul-17 10:26
memberPongavanam18-Jul-17 10:26 
QuestionAllow only Integer and float value inside the text box with in the gridview control Pin
Pongavanam18-Jul-17 5:20
memberPongavanam18-Jul-17 5:20 
AnswerRe: Allow only Integer and float value inside the text box with in the gridview control Pin
Tadit Dash (ତଡିତ୍ କୁମାର ଦାଶ)3-Aug-17 2:19
protectorTadit Dash (ତଡିତ୍ କୁମାର ଦାଶ)3-Aug-17 2:19 
GeneralMy vote of 5 Pin
kirills15-Oct-15 8:49
memberkirills15-Oct-15 8:49 
GeneralRe: My vote of 5 Pin
Tadit Dash (ତଡିତ୍ କୁମାର ଦାଶ)16-Oct-15 7:32
protectorTadit Dash (ତଡିତ୍ କୁମାର ଦାଶ)16-Oct-15 7:32 
QuestionGridview Edit Mode Pin
esb779-Nov-14 16:38
memberesb779-Nov-14 16:38 
AnswerRe: Gridview Edit Mode Pin
Tadit Dash (ତଡିତ୍ କୁମାର ଦାଶ)3-Mar-15 3:02
protectorTadit Dash (ତଡିତ୍ କୁମାର ଦାଶ)3-Mar-15 3:02 
GeneralRe: Gridview Edit Mode Pin
esb773-Mar-15 4:27
memberesb773-Mar-15 4:27 
GeneralRe: Gridview Edit Mode Pin
Tadit Dash (ତଡିତ୍ କୁମାର ଦାଶ)3-Mar-15 20:50
protectorTadit Dash (ତଡିତ୍ କୁମାର ଦାଶ)3-Mar-15 20:50 
GeneralRe: Gridview Edit Mode Pin
esb774-Mar-15 4:48
memberesb774-Mar-15 4:48 
GeneralRe: Gridview Edit Mode Pin
Tadit Dash (ତଡିତ୍ କୁମାର ଦାଶ)4-Mar-15 18:54
protectorTadit Dash (ତଡିତ୍ କୁମାର ଦାଶ)4-Mar-15 18:54 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Technical Blog
Posted 30 Jul 2014


6 bookmarked