如何使用Ajax Control Toolkit(CalendarExtender)验证字符串日期?

时间:2013-06-19 18:49:29

标签: c# javascript asp.net ajax

  

我有两个格式化的TexBox,并通过CalendarExtender获取其文本值,我想验证第一个大于第二个;然而,它们是以字符串形式出现而不是日期。我该如何验证?这是我的asp代码:

<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>
  

在背后的代码中:

    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 = "";
    }

}
  

感谢您的帮助!

2 个答案:

答案 0 :(得分:2)

您可以使用comparevalidator并将“Type”设置为“Date”。

喜欢这个。

<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();

答案 1 :(得分:0)

DateTime dt1;
DateTime dt2;
if (DateTime.TryParse(TextBox1.Text, out dt1) && DateTime.TryParse(TextBox2.Text, out dt2) && dt1 <= dt2)
throw new Exception("I do not like this.");