Ajax CalendarExtender - Date Validation

I've just been asked to find a solution to stop users choosing dates in the past in a calendarextender control.  After using a little google-phoo, I found a couple of solutions which involved extending the extender itself.  Altering the calendar.js then recompiling it and putting it back into your solution.  That just seems a bit excessive to me.  So I got to thinking couldn't I just use some in page JavaScript to trap the date entered. The Solution was pretty simple:

First we add a text box and a calendarextender:

<asp:TextBox ID="txtDate" MaxLength="10" runat="server" ReadOnly="True"></asp:TextBox>
<
cc1:CalendarExtender ID="CalendarExtender1" runat="server" Format="dd/MM/yyyy" TargetControlID="txtDate" OnClientDateSelectionChanged="checkDate">
</cc1:CalendarExtender>  

you may notice that the CalendarExtender has an event attached (checkDate) - this is the JavaScript function you want it to call when ever you select a new date, add this function the top of your aspx page:  

<script type="text/javascript">
    function checkDate(sender,args)
    {
    //create a new date var and set it to the
    //value of the senders selected date
    var selectedDate = new Date();
    selectedDate = sender._selectedDate;
    //create a date var and set it's value to today
    var todayDate = new Date();
    var mssge = "";

    if(selectedDate < todayDate)
     {
        //set the senders selected date to today
        sender._selectedDate = todayDate;
        //set the textbox assigned to the cal-ex to today
        sender._textbox.set_Value(sender._selectedDate.format(sender._format));
        //alert the user what we just did and why
        alert("Warning! - Date Cannot be in the past");
     }
    }

    </script>

 Simple and the nice thing is it's reusable for all the calendarextenders on your page, just add the checkDate function to your other extenders.  

Happy Coding

 


Posted by: Dean
Posted on: 10/26/2008 at 9:25 AM
Tags: , , , ,
Actions: E-mail | Kick it! | DZone it! | del.icio.us
Post Information: Permalink | Comments (3) | Post RSSRSS comment feed