2013-06-19 161 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

相關問題