ASP.NET Ajax CalendarExtender and Validation

1 08 2008

ASP.NET Ajax toolkit has a CalendarExtender control which is very cool as you can associate the CalendarExtender to a a TextBox and also to a Button/ImageButton so that you can popup the calendar.

Below is the code to get started with CalendarExtender:

<asp:TextBox 
    ID="TextBox1" 
    runat="server" 
    width="300pt" />
<asp:ImageButton 
    ID="btnCalenderPopup"
    Width="16" Height="16" 
    runat="server" 
    ImageUrl="~/images/calender.bmp" 
    CausesValidation="False" />
<ajaxToolkit:CalendarExtender 
    ID="CalendarExtender1"
    runat="server" 
    TargetControlID="TextBox1" 
    PopupButtonID="btnCalenderPopup" 
    Format="dd/MM/yyyy" />

And here is the output:

calender-extender-1

and,

calender-extender-2

Wait! What’s that grayed text in the textbox that says – Enter the Date of Birth (dd/mm/yyyy)

Certainly that’s not the part of CalendarExtender 🙂 , but part of ASP.NET Ajax Toolkit 8) . We can use the TextBoxWatermarkExtender which can display watermarked (grayed) texts on controls. Below is the code for our CalendarExtender :

<ajaxToolkit:TextBoxWatermarkExtender  
    ID="WatermarkExtender1"
    runat="server" 
   TargetControlID="TextBox1" 
   WatermarkCssClass="watermarked" 
   WatermarkText="Enter the Date of Birth (dd/mm/yyyy)" />

And below is the CSS style that’s used with this watermark extender :

.watermarked
{
    color: #C0C0C0;
    font-style: italic;
}

All looks good now and the user is happy the way Calendar pops up, choosing the date and also the fact that he can type in the date in the textbox in the desired format. Now comes the problem – Date Validation! – How are we going to validate the entered date? – I had to validate that the date entered is not more than today’s date.

There are two ways to do it :

1) Using Javascript (with our CalendarExtender)

2) Using RangeValidators for our textbox

Using Javascript:

The CalendarExtender has a property called OnClientDateSelectionChanged which can be set to a piece of javascript which can do the job for us. Below is the code:

<ajaxToolkit:CalendarExtender
    ID="CalendarExtender1"
     runat="server" 
    TargetControlID="TextBox1"
    PopupButtonID="btnCalenderPopup" 
    OnClientDateSelectionChanged="checkMyDate"
    Format="dd/MM/yyyy" />

and below is the javascript:

<script type="text/javascript">
function checkDate(sender,args)
{
    var dt = new Date();        
    if(sender._selectedDate > dt)
    {
        sender
            ._textbox
            .set_Value(dt.format(sender._format));
    }
}
</script>

Using RangeValidator:

Since we use a TextBox control to display our date once we choose from the calendar or to manually input the date, RangeValidators can be used to check whether the date is within a given range (minimum & maximum). Below is the code for RangeValidator :

<asp:RangeValidator 
    ID="RangeValidator1"
    runat="server" 
    ControlToValidate="TextBox1" 
    ErrorMessage="*Please enter proper date" 
    Type="Date" Display="Dynamic" />

And in your page load event we can set our maximum and minimum date values :

RangeValidator1.MinimumValue 
      = new DateTime(1600, 01, 01).ToString("dd/MM/yyyy");
RangeValidator1.MaximumValue 
     = DateTime.Now.ToString("dd/MM/yyyy");

With these two methods you can easily validate the date. And yes, using both would sometimes lead you to race conditions where choosing a date from the calendar might be an invalid date and the RangeValidators would immediately come to the focus.

Advertisements

Actions

Information

13 responses

11 09 2008
Radhika

In the above code u r giving the CalendarExtender property OnClientDateSelectionChanged for date validation.U gave the name like checkMyDate but in the javascript u r giving the function name like checkDate
by using this code i am not rectifying my problem.Still i get the validation problem.

13 11 2008
Cris

GREAT!!
it wass very helpfull!!! Graciassssss…

12 03 2009
sangam uprety

Hi,
Date validation in asp.net textbox has always been a genuine need. Although we could do it using validator control in asp.net, use of javascript is always appreciated. Here goes another simple method: http://dotnetspidor.blogspot.com/2009/03/using-javascript-for-validation-of.html

Happy Programming!

14 01 2010
Mukesh Rana

I m using javascript. but i want to set my textBox to the Previous value not the current date.

9 02 2010
Mark Alvin

It’s not working for me. My code is:

function checkDate(sender,args)
{
var dt = new Date();
if(sender._selectedDate > dt)
{
sender
._textbox
.set_Value(dt.format(sender._format));
}
}

Inquiries for the Day

 Date:

 

 Number of Inquiries:

Comments:

My CodeBehind is:

protected void Page_Load(object sender, EventArgs e)
{

if (!IsPostBack)
{
txtInquiry.Attributes.Add(“onkeypress”, “return numeralsOnly(event)”);
txtCreatedDate.Text = DateTime.Today.ToLongDateString();

RangeValidator1.MinimumValue = new DateTime(1600, 01, 01).ToString(“MM/dd/yyyy”);
RangeValidator1.MaximumValue = DateTime.Now.ToString(“MM/dd/yyyy”);

23 04 2010
Ranjit Kumar

I am using an ImageButton to popup the calendar with CausesValidation turned off. I am encountering two issues: Key one being, upon selecting a date using the calendar, the regular validation control fires displaying error message, even though there is no issue with the selected date format.

Second one being, when the calendar is popped up, pressing escape doesn’t collapse the calendar. Does anyone here know a javascript/jscript magic to collapse?

28 08 2010
sameera

i have a proble. how to registor ajax tool kit in my page. pls help soon
thanks a lot

26 05 2011
Dinesh

Hi,

Ajax Calendar control is Excellent when you use it with a single textbox.But how can we achieve needs like coparing the date from another texbox live EffectivefromDate in one TextBox and EffectiveToDate in another TextBox whose values are driven from Ajax Calendar control dynamically.I can set Range validator since my from or To date changes dynamically.I also like my page to get postback frequently.I achieved this through TextChange Event.but i want to know how to disable the dates which is populated in Ajax Calendar based on my from and To date at run time on script,since we can write script in Ajax Calendar Extenders OnClientShowing Event…

Thanks in Advance….

23 06 2011
Harish

It is getting error for using validator

The value ’23/6/2011′ of the MaximumValue property of ‘validdateofbirth’ cannot be converted to type ‘Date’.

Exception Details: System.Web.HttpException: The value ’23/6/2011′ of the MaximumValue property of ‘validdateofbirth’ cannot be converted to type ‘Date’.

13 09 2011
Brij

Very helpful,
Thanks

28 02 2012
jojemar

Gud Day ..

I have two textboxes with Calendarextenders in each one, so when i choose a date from Calendarextnder1 it will show in the textbox1 and when i choose at Calendar2 it will show in textbox2 .. my question is how to get the number of days in another textbox.

example i chose 2/28/2012 and 2/29/2012 number of days is 1 right .. so how to do it?? i need help TY for replies

6 02 2013
Simbu

Use Datediff function

28 03 2013
jayeshsorathia

Very useful article

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s




%d bloggers like this: