Introduction

Many a times it is better to use Server Side Validations in Web Application with Client Side Validations, below is the example of validating Dates using Custom Validator.

.Aspx page

<asp:TextBox runat="server" ID="txtToEndDate" CssClass="TextBoxSearch" MaxLength="100" TabIndex="0"></asp:TextBox><asp:CustomValidator ID="CustomValidator1" OnServerValidate="CustomValidator1_ServerValidate"
runat="server" Display="None" ErrorMessage="" ValidationGroup="GroupName"></asp:CustomValidator>

.Aspx page.cs

protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
{
try

{
if
((!string.IsNullOrEmpty(this.txtToEndDate.Text)) && (!string.IsNullOrEmpty(this.txtFromStartDate.Text)))
{
if
(Convert.ToDateTime(this.txtToEndDate.Text) < Convert.ToDateTime(this.txtFromStartDate.Text))
{
args.IsValid = false;
Message.ClearMessage();
Message.MessageId = "To End Date should not be less than From Start Date";
Message.ShowMessage();
Gridview.Visible = false;
}

}

if
(string.IsNullOrEmpty(this.txtFromStartDate.Text))

{
args.IsValid = false;
Message.ClearMessage();
Message.MessageId = "From Start Date Cannot be Blank";
Message.ShowMessage();
Gridview.Visible = false;
}
if
(string.IsNullOrEmpty(this.txtToEndDate.Text))

{

args.IsValid = false;
Message.ClearMessage();
Message.MessageId = "To End Date Cannot be Blank ";
Message.ShowMessage();
Gridview.Visible = false;
}
if
((string.IsNullOrEmpty(this.txtToEndDate.Text)) && (string.IsNullOrEmpty(this.txtFromStartDate.Text)))
{
args.IsValid = false;
Message.ClearMessage();
Message.MessageId = "From Start Date and To End Date cannot be blank";
Message.ShowMessage();
Gridview.Visible = false;
}
}
catch
(FormatException e)
{
args.IsValid = false;
CustomValidator1.ErrorMessage = "Invalid Date." + e.Message;
}
}