Custom Date Validation in ASP.Net

The validators shipped with .NET are great tools to check and validate what the user enters on a web form, before processing it. With the DateValidator control this gap has been filled. User can insert date in a common text box and that’s all: you won’t have to bother about validating their input, the only request is that the date must be in the format dd/mm/yyyy or user defined format.

Let us get in to the code.

A RangeValidatorwould work here to check the date is greater than today:

<asp:RangeValidator ID=”RangeValidator1″ runat=”server” ControlToValidate=”txt_start_date” Display=”None” ErrorMessage=”Date must be greater than today” Type=”Date”></asp:RangeValidator>

<cc1:ValidatorCalloutExtender ID=”ValidatorCalloutExtender4″ runat=”server” Enabled=”True”                                                       TargetControlID=”RangeValidator1″></cc1:ValidatorCalloutExtender>

Code Behind:

  RangeValidator1.MinimumValue = DateTime.Now.Date.ToString(“dd/MM/yyyy”);
RangeValidator1.MaximumValue = System.DateTime.MaxValue.ToString(“dd/MM/yyyy”);

If you want to do comparison between two dates we can use  compare validator:

<asp:CompareValidator ID=”CompareValidator5″ runat=”server” Operator=”GreaterThan”   Type=”Date” Display=”None” ErrorMessage=”EndDate must be greater than StartDate”   ControlToValidate=”txt_end_date” ControlToCompare=”txt_start_date”></asp:CompareValidator>
<cc1:ValidatorCalloutExtender ID=”ValidatorCalloutExtender5″ runat=”server” Enabled=”True” TargetControlID=”CompareValidator5″> </cc1:ValidatorCalloutExtender>

You can use any (Operator=”GreaterThan” ) like LessThan,Equal ,etc.,

I attached some pieces of image for the reference of output:


If  it is not working add the below line in web.config file under <system.web>

<globalization requestEncoding=”utf-8″ responseEncoding=”utf-8″ culture=”en-GB” uiCulture=”en”/>

Happy Coding….

Permanent link to this article:

Leave a Reply

Your email address will not be published.