2013-08-20 172 views
1

我正在處理髮票的日期字段。爲發票日期選擇的日期不能是當前月份以外的任何日期。驗證當前月份中的日期

這裏是我的代碼:

at Page_Load: 
Dim firstOfTheMonthDate As DateTime = FirstDayOfMonthFromDateTime(DateTime.Now) 
       Me.compareValidatorDate.ValueToCompare = firstOfTheMonthDate.ToString("d") 

我的專用功能

Private Function FirstDayOfMonthFromDateTime(dateTime As DateTime) As DateTime 
     Return New DateTime(dateTime.Year, dateTime.Month, 1) 
    End Function 

客戶端:

<asp:Label ID="lblInvDate" runat="server" AssociatedControlID="txtInvDate">Invoice Date:</asp:Label> 
        <asp:TextBox runat="server" ID="txtInvDate" MaxLength="20" CssClass="L5 DateCal" /> 
        <asp:RequiredFieldValidator ID="RequiredFieldValidator1" ControlToValidate="txtInvDate" 
        Text="The date field is required!" runat="server" /> 
        <asp:CompareValidator ID="compareValidatorDate" ControlToValidate="txtInvDate" 
        Type="Date" Operator="LessThan" ErrorMessage="Date must be from this month!" 
        Display="Dynamic" runat="server" /> 

我遇到的問題是,確認不會發生,或至少,如果輸入的日期不是空白或空白,則保存發票日期。我如何改進我的代碼?

信用卡爾安德森幫助代碼。

+2

您的驗證說明在txtInvDate中輸入的值必須小於任意月份的第一天。這似乎不是您所說的驗證行爲,您希望它大於或等於當前月份的第一個月份,並且小於或等於當前月份的最後一天。我對您的要求的理解是否正確? – Adrian

+1

@阿德里安 - 感謝您注意到,我已經把它放在了腦海中,但是寫下了與您所說的完全相反的邏輯。 –

+0

是的阿德里安,絕對正確。 – JettyJetty

回答

2

我很抱歉沒有注意到這一點,但我早些給了你不正確的邏輯。

較好的解決辦法是使用RangeValidator,像這樣:

代碼隱藏(Page_Load):

Dim firstOfTheMonthDate As DateTime = FirstDayOfMonthFromDateTime(DateTime.Now) 
Dim endOfTheMonthDate As DateTime = LastDayOfMonthFromDateTime(DateTime.Now) 
Me.rangeValidatorDate.MinimumValue = firstOfTheMonthDate.ToString("d") 
Me.rangeValidatorDate.MaximumValue = endOfTheMonthDate.ToString("d") 

代碼隱藏(效用函數):

Private Function FirstDayOfMonthFromDateTime(dateTime As DateTime) As DateTime 
    Return New DateTime(dateTime.Year, dateTime.Month, 1) 
End Function 

Public Function LastDayOfMonthFromDateTime(dateTime As DateTime) As DateTime 
    Dim firstDayOfTheMonth As New DateTime(dateTime.Year, dateTime.Month, 1) 
    Return firstDayOfTheMonth.AddMonths(1).AddDays(-1) 
End Function 

客戶端:

<asp:Label ID="lblInvDate" runat="server" AssociatedControlID="txtInvDate">Invoice Date:</asp:Label> 
<asp:TextBox runat="server" ID="txtInvDate" MaxLength="20" CssClass="L5 DateCal" /> 
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" ControlToValidate="txtInvDate" 
    Text="The date field is required!" runat="server" /> 
<asp:RangeValidator id="rangeValidatorDate" runat="server" 
    ControlToValidate="txtInvDate" Type="Date" Display="Dynamic" /> 
+2

因爲最初的要求是讓日期「在當前月份內」,所以'rangeValidatorDate.MaximumValue'應該是'new DateTime(DateTime.Now.Year,DateTime.Now.Month,DateTime.DaysInMonth(DateTime.Now。 Year,DateTime.Now.Month));'。這是一個滿口,但它應該給當月的最後一天。 – Adrian

+1

@阿德里安 - 哇,我今天不在。好看。更新了答案。 –

+0

謝謝阿德里安和卡爾。我只是得到了足夠的代表給實際的道具,所以我會。我非常感謝他的幫助,並且我能夠解釋代碼在我所需的斷點之間的每一步中實際執行的操作。調試進展順利。 – JettyJetty

相關問題