In this article I will explain with an example, how to implement Date Range Validation in
AJAXControlToolkit CalendarExtender Control in ASP.Net using C# and VB.Net.
Download latest AJAX Control Toolkit
Registering ASP.Net AJAX Control Toolkit
<%@Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>
HTML Markup
The following HTML Markup consists of:
ToolkitScriptManager – For managing the
AJAX components in the page.
TextBox – For capturing date.
The TextBox has been assigned with following Property –
ReadOnly – For preventing users from editing.
RangeValidator – For specifying upper and lower boundary of date.
The RangeValidator consists of following properties:
Type – For Specifying the type, here it is date.
ControlToValidate – It has been set with the ID of the TextBox to which CalendarExtender is applied.
MinimumValue – For specifying minimum value of the range.
MaximumValue – For specifying maximum value of the range.
CalendarExtender – For selecting date.
Button – For validating selected date.
<cc1:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server"></cc1:ToolkitScriptManager>
Select Date:
<asp:TextBox ID="txtDate" runat="server" ReadOnly="true"></asp:TextBox>
<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="OnSubmit" />
<br/><br/>
<asp:RangeValidator ID="RangeValidator1" runat="server" Type="Date" ControlToValidate="txtDate"
MinimumValue="2024/06/01" MaximumValue='2024/06/20' ForeColor="Red" ErrorMessage="Date should be between 01/06/2024 and 20/06/2024."
Display="Dynamic"/>
<cc1:CalendarExtender ID="Calender1" runat="server" TargetControlID="txtDate"></cc1:CalendarExtender>
Fetching the value of the Selected Date on Server Side
When the
Submit button clicked, the value of the Selected Date is fetched from the
Request.Form collection and it is displayed using
JavaScript Alert Message Box.
Note:
Request.Form collection is used as in some browsers the
Text property does not hold the value set from
JavaScript when the TextBox is set as
ReadOnly.
C#
protected void OnSubmit(object sender, EventArgs e)
{
string dt = Request.Form[txtDate.UniqueID];
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Your Selected date: " + dt + "');", true);
}
VB.Net
Protected Sub OnSubmit(ByVal sender As Object, ByVal e As EventArgs)
Dim dt As String = Request.Form(txtDate.UniqueID)
ClientScript.RegisterStartupScript(Me.GetType(), "alert", "alert('Your Selected date: " & dt & "');", True)
End Sub
Screenshot
Demo
Downloads