I have two TexBoxes that are formatted and get their text value by a CalendarExtender, and I would like to validate the first one greater than the second one; however, they are coming in as a string and not as date. How can I validate that? This is my asp code:
<asp:TextBox ID="TextBox1" runat="server" style="width:160px; text-align:center;" OnServerValidate="DateRange_ServerValidate"></asp:TextBox>
<asp:TextBox ID="TextBox2" runat="server" style="width:160px; text-align:center;" OnServerValidate="DateRange_ServerValidate"></asp:TextBox>
<asp:Label ID="lblDateError" runat="server" ForeColor="#CC0000" ></asp:Label>
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
</asp:ToolkitScriptManager>
<asp:CalendarExtender ID="CalendarExtender1" runat="server" Format="dddd, MMMM dd yyyy"
TargetControlID="TextBox1" PopupButtonID="Image1">
</asp:CalendarExtender>
<asp:CalendarExtender ID="CalendarExtender2" runat="server" Format="dddd, MMMM dd yyyy"
TargetControlID="TextBox2" PopupButtonID="Image4">
</asp:CalendarExtender>
In the code behind:
protected void DateRange_ServerValidate(object sender, EventArgs args)
{
DateTime ToDate = DateTime.ParseExact(TextBox1.Text.ToString(), "dddd, MMMM dd yyyy", CultureInfo.InvariantCulture);
DateTime currentdate = DateTime.ParseExact(TextBox2.Text.ToString(), "dddd, MMMM dd yyyy", CultureInfo.InvariantCulture);
if (ToDate < currentdate)
{
lblDateError.Visible = true;
lblDateError.Text = "End Date should not be earlier than the current date.";
return;
}
else
{
lblDateError.Text = "";
}
}
Thanks for the help!
最佳答案
您只需使用比较验证器并将“类型”设置为“日期”即可。
像这样。
<asp:TextBox ID="Textbox1" runat="server"></asp:TextBox>
<ajaxToolkit:CalendarExtender ID="CalendarExtender2" runat="server" TargetControlID="Textbox1"></ajaxToolkit:CalendarExtender>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<ajaxToolkit:CalendarExtender ID="CalendarExtender1" runat="server" TargetControlID="TextBox2"></ajaxToolkit:CalendarExtender>
<asp:CompareValidator ID="CompareValidator1" ControlToCompare="Textbox1" Operator="LessThan"
ControlToValidate="TextBox2" Type="Date" runat="server" ErrorMessage="Invalid Date Range"></asp:CompareValidator>
<asp:Button runat="server" Text="validate"/>
要在服务器上验证这一点,您只需调用
CompareValidator1.Validate();
关于c# - 如何使用 Ajax Control Toolkit (CalendarExtender) 验证字符串日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17199021/