2013-06-19 83 views
0

我有两个格式化并通过CalendarExtender获取文本值的TexBox,我想验证第一个大于第二个的TextBox,然而,它们是作为一个字符串而不是日期而来的。我如何验证?这是我的ASP代码:如何使用Ajax Control Toolkit(CalendarExtender)验证字符串日期?

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

} 

感谢您的帮助!

+0

在'DateRange_ServerValidate'方法是什么?你可以使用'DateTime.ParseExact'将字符串转换为日期时间吗? –

+0

我试过了上面的代码,但它并没有启动。 (请参阅编辑问题) – Jacman

+0

你如何触发你的验证?有没有提交按钮或其他东西? –

回答

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

非常感谢CompareValidator做到了! – Jacman

+0

没问题,乐意帮忙 – Smeegs

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."); 
+0

谢谢,我试过你的代码,但它不会引发异常。 – Jacman

相关问题