Resources » Code Snippets » ASP.NET GridView

Date Validation in GridView


Posted Date: 14-Oct-2009  Last Updated:   Category: ASP.NET GridView    
Author: Member Level: Gold    Points: 35



Date Validation in GridView



Introduction



I will explain about how to validate date entered in a TextBox control inside a GridView. Sometimes you may need to capture DateTime value in a TextBox inside a GridView control and need to validate before saving to database. This validation will happen when clicking a button, for example, clicking a Save button.

Logic



Here I have validated the date value using server side C# code. The following logic is used to perform the validation.

1. The IsValidDate() function in this code snippet accepts a date value given in string and returns true or false after validating the input.

2. Inside IsValidateDate() function, there are two validation are performed. The first validation checks whether the value is in dd/mm/yyyy format using Regular Expression. It returns false if the format is not valid and the execution does not continue.

3. If the first validation is successful, the second validation in IsValidateDate () checks whether the date value is a valid date using British format. I have used System.IFormatProvider class to do this.

4. The validation is then called in the click event of the btnSave control. The value of the txtDOJ control in each row of the GridView is extarcted using a for loop and checked whether the value entered in the TextBox is a valid date by calling IsValidateDate() function. If the validation fails for a particular GridView row, it will display the row number where the date validation fails.

Code Snippet – aspx



The following aspx code snippet has a GridView and CustomValidator. The date value is captured in a TextBox in a TemplateField of the GridView. The CustomValidator is used to display error message after validation.


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DemoPage28.aspx.cs" Inherits="DemoPage28" %>

<!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">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table width="100%">
<tr>
<td>
<asp:CustomValidator ID="cvValidateDate" runat="server" ErrorMessage="CustomValidator"></asp:CustomValidator>
</td>
</tr>
<tr>
<td>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
PageSize="5">
<Columns>
<asp:BoundField DataField="EmpCode" HeaderText="Employee Code">
<ItemStyle Width="125px" />
</asp:BoundField>
<asp:BoundField DataField="EmpName" HeaderText="Name">
<ItemStyle Width="250px" />
</asp:BoundField>
<asp:TemplateField HeaderText="DOJ">
<ItemTemplate>
<asp:TextBox ID="txtDOJ" Width="120px" Text='<%#DataBinder.Eval(Container.DataItem, "DOJ") %>'
runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</td>
</tr>
<tr>
<td>
<asp:Button ID="btnSave" runat="server" Text="Save" onclick="btnSave_Click" />
</td>
</tr>
</table>
</div>
</form>
</body>
</html>



Code Snippet – C#



The following server side code in C# has code to populate the GridView with sample data, IsValidateDate() function and Click event of Save button.


using System;
using System.Web.UI.WebControls;
using System.Data;
using System.Text.RegularExpressions;


public partial class DemoPage28 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridView();
}
}

private void BindGridView()
{
DataTable dtEmp = new DataTable();

dtEmp.Columns.Add("EmpCode", System.Type.GetType("System.Int16"));
dtEmp.Columns.Add("EmpName", System.Type.GetType("System.String"));
dtEmp.Columns.Add("DOJ", System.Type.GetType("System.DateTime"));

dtEmp.Rows.Add(new object[] { 1001, "Kannan", null });
dtEmp.Rows.Add(new object[] { 1002, "Arun", null });
dtEmp.Rows.Add(new object[] { 1003, "Jackson", null });
dtEmp.Rows.Add(new object[] { 1004, "Raja", null });
dtEmp.Rows.Add(new object[] { 1005, "John", null });
dtEmp.Rows.Add(new object[] {1006, "Dinesh", null});

dtEmp.Rows.Add(new object[] { 1007, "Kannan", null });
dtEmp.Rows.Add(new object[] { 1008, "Arun", null });
dtEmp.Rows.Add(new object[] { 1009, "Jackson", null });
dtEmp.Rows.Add(new object[] { 1010, "Raja", null });
dtEmp.Rows.Add(new object[] { 1011, "John", null });
dtEmp.Rows.Add(new object[] { 1012, "Dinesh", null });

GridView1.DataSource = dtEmp;
GridView1.DataBind();
}
protected void btnSave_Click(object sender, EventArgs e)
{
foreach (GridViewRow grow in GridView1.Rows)
{
string strDate = (grow.FindControl("txtDOJ") as TextBox).Text;
if (!String.IsNullOrEmpty(strDate) && !IsValidDate(strDate))
{
cvValidateDate.ErrorMessage = "Invalid date entered in row number " + (grow.RowIndex + 1);
cvValidateDate.IsValid = false;
return;
}
}
}

public static bool IsValidDate(string date)
{
try
{
StringBuilder sb = new StringBuilder();
sb.Append(@"\b([0-9]{1,2}[\s]?[\-/\.\–][\s]?[0-9]{1,2}[\s]?[\-/\.\–][\s]?");
sb.Append(@"[0-9]{2,4})\b|\b(([0-9]{1,2}[TtHhSsRrDdNn]{0,2})[\s]?[\-/\.,\–]?[\s]");
sb.Append(@"?([Jj][Aa][Nn][Uu]?[Aa]?[Rr]?[Yy]?|[Ff][Ee][Bb][Rr]?[Uu]?[Aa]?[Rr]?[Yy]?");
sb.Append(@"|[Mm][Aa][Rr][Cc]?[Hh]?|[Aa][Pp][Rr][Ii]?[Ll]?|[Mm][Aa][Yy]|[Jj][Uu][Nn][Ee]?");
sb.Append(@"|[Jj][Uu][Ll][Yy]?|[Aa][Uu][Gg][Uu]?[Ss]?[Tt]?|[Ss][Ee][Pp][Tt]?[Ee]?[Mm]?");
sb.Append(@"[Bb]?[Ee]?[Rr]?|[Oo][Cc][Tt][Oo]?[Bb]?[Ee]?[Rr]?|[Nn][Oo][Vv][Ee]?[Mm]?[Bb]?");
sb.Append(@"[Ee]?[Rr]?|[Dd][Ee][Cc][Ee]?[Mm]?[Bb]?[Ee]?[Rr]?)[\s]?[\-/\.,\–]?[\s]?[']?([0-9]");
sb.Append(@"{2,4}))\b|\b(([Jj][Aa][Nn][Uu]?[Aa]?[Rr]?[Yy]?|[Ff][Ee][Bb][Rr]?[Uu]?[Aa]?[Rr]?");
sb.Append(@"[Yy]?|[Mm][Aa][Rr][Cc]?[Hh]?|[Aa][Pp][Rr][Ii]?[Ll]?|[Mm][Aa][Yy]|[Jj][Uu][Nn][Ee]?");
sb.Append(@"|[Jj][Uu][Ll][Yy]?|[Aa][Uu][Gg][Uu]?[Ss]?[Tt]?|[Ss][Ee][Pp][Tt]?[Ee]?[Mm]?[Bb]?[Ee]?");
sb.Append(@"[Rr]?|[Oo][Cc][Tt][Oo]?[Bb]?[Ee]?[Rr]?|[Nn][Oo][Vv][Ee]?[Mm]?[Bb]?[Ee]?[Rr]?|[Dd][Ee]");
sb.Append(@"[Cc][Ee]?[Mm]?[Bb]?[Ee]?[Rr]?)[\s]?[,]?[\s]?[0-9]{1,2}[TtHhSsRrDdNn]{0,2}[\s]?[,]?[\s]");
sb.Append(@"?[']?[0-9]{2,4})\b");

Regex reDate = new Regex(sb.ToString());

Match mDate = reDate.Match(date);
if (!mDate.Success)
return false;

System.IFormatProvider ifpformat = new System.Globalization.CultureInfo("en-GB", true);
DateTime tempDate = Convert.ToDateTime(date, ifpformat);
if ((tempDate.Year > 1900) && (tempDate.Year < 2100))
return true;
else
return false;

}
catch (System.FormatException)
{
return false;
}
}


}



Did you like this resource? Share it with your friends and show your love!

Responses to "Date Validation in GridView"

No responses found. Be the first to respond...

Feedbacks      

Post Comment:




  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:   Sign In to fill automatically.
    Email: (Will not be published, but required to validate comment)



    Type the numbers and letters shown on the left.


    Submit Article     Return to Article Index

    Subscribe to Subscribers
    Active Members
    TodayLast 7 Daysmore...

    Awards & Gifts
    Talk to Webmaster Tony John

    Online Members

    Ashutosh Jha
    More...
    Copyright © SpiderWorks Technologies Pvt Ltd., Kochi, India