Step 1:- Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Demo.Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table>
<tr>
<td>Date
(dd/MM/yyyy)</td>
<td>
<asp:TextBox ID="txtDate" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td colspan="2">
<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" />
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
Step 2:- Default.aspx.cs
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Demo
{
public partial class Default :
System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
}
}
#region Validation
Methods
public static bool IsDate(string strDate)
{
string strPattern
= @"^(((0?[1-9]|[12]\d|3[01])[\.\-\/](0?[13578]|1[02])[\.\-\/]((1[6-9]|[2-9]\d)?\d{2}|\d))|((0?[1-9]|[12]\d|30)[\.\-\/](0?[13456789]|1[012])[\.\-\/]((1[6-9]|[2-9]\d)?\d{2}|\d))|((0?[1-9]|1\d|2[0-8])[\.\-\/]0?2[\.\-\/]((1[6-9]|[2-9]\d)?\d{2}|\d))|(29[\.\-\/]0?2[\.\-\/]((1[6-9]|[2-9]\d)?(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00)|00|[048])))$";
Regex objPattern= new Regex(strPattern, RegexOptions.IgnoreCase);
return objPattern.IsMatch(strDate);
}
public static bool IsFutureDate(string strDate)
{
if (Convert.ToDateTime(DateTime.ParseExact(strDate, "dd/MM/yyyy", CultureInfo.InvariantCulture).ToString("MM/dd/yyyy", CultureInfo.InvariantCulture))
> System.DateTime.Today)
{
return true;
}
else
{
return false;
}
}
#endregion
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(txtDate.Text))
{
DisplayMessage("Date
field cannot be blank.");
txtDate.Focus();
return;
}
else
{
if (!IsDate(txtDate.Text))
{
DisplayMessage("Please
enter valid Date. Date should be dd/MM/yyyy");
txtDate.Focus();
return;
}
else
{
if (IsFutureDate(txtDate.Text))
{
DisplayMessage("Entered
date is greater than current date.");
txtDate.Focus();
return;
}
}
}
}
#region DisplayMessage
protected void DisplayMessage(string strMsg)
{
strMsg
= strMsg.Replace("\r\n", "\\n");
strMsg
= strMsg.Replace("\n", "\\n");
strMsg
= strMsg.Replace("'", "");
string scriptString
= @"<script
language=""JavaScript"">";
scriptString
+= "alert('" + strMsg + "');";
scriptString
+= "</script>";
ClientScript.RegisterStartupScript(this.GetType(), "Startup",
scriptString);
}
#endregion
}
}
No comments:
Post a Comment