我有兩個格式化並通過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 = "";
}
}
感謝您的幫助!
在'DateRange_ServerValidate'方法是什麼?你可以使用'DateTime.ParseExact'將字符串轉換爲日期時間嗎? –
我試過了上面的代碼,但它並沒有啓動。 (請參閱編輯問題) – Jacman
你如何觸發你的驗證?有沒有提交按鈕或其他東西? –