0

我有两个 TexBoxes,它们被格式化并通过 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 = "";
    }

}

谢谢您的帮助!

4

2 回答 2

2

您可以只使用 comparevalidator 并将“类型”设置为“日期”。

像这样。

<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();
于 2013-06-19T19:29:52.697 回答
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.");
于 2013-06-19T18:56:25.740 回答