I have been using the build in Validator controls that come with ASP.NET and have found them very useful. I especially like the regular expression validator as it works as a great backup when there is nothing else available. However the need came up for me to validate a couple of date text fields that I was using with the new AJAX Toolkit Calendar Control. The control is awesome for providing a quick and simple drop-down date picker with almost no extra coding. However it does not validate that the date in the text box is a valid date format. As it turns out, there is a really easy way to do this with the CompareValidator control. Here is how I did this…

1. Before adding the date picker control, you must ensure the AJAX Toolkit is registered. Add this line at the top of the page right after the @Page directive:

        <%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit"
                     TagPrefix="ajaxToolkit" %>

2. If you have not already done so anywhere else (such as your master page), you also need to add a ScriptManager to the page.

        <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>

3. In the ASPX page add the following controls to give you a date picker with a drop-down graphic that displays the calendar control when clicked:

        <asp:Label ID="lblDate" runat="server" Text="Date: "></asp:Label>
        <asp:TextBox ID="txtDate" runat="server" Width="140px"></asp:TextBox>
        <asp:Image ID="imgCalendar" runat="server" ImageUrl="~/Images/Calendar.png" />
        <ajaxToolkit:CalendarExtender ID="CalendarExtender1" runat="server"
              
TargetControlID="txtDate" Format="MM/dd/yyyy"
              
PopupButtonID="imgCalendar" />

4. Now to ensure that the date entered in the text box is a valid parse-able date, simply add this one extra control to the page:

        <asp:CompareValidator ID="CompareValidator1" runat="server"
               ControlToValidate="txtDate" ErrorMessage="* Enter a valid date"
               Operator="DataTypeCheck" Type="Date" ValidationGroup="grpDate" />

Make sure you set the Operator attribute to DataTypeCheck and the Type to Date and when you click on whatever button you have on your page that triggers a postback, the validator will try to parse the date into a DateTime and display the message if that fails. Of course, you also need to ensure that your button (or whatever) has CausesValidation set to true (the default) or the Validator will not trigger.

That's it! You now have a very cool drop-down date picker with validation and all with no coding involved.