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" />

我遇到的问题是验证不会发生,或者至少,如果输入的任何日期不是空白或空值,发票日期就会被保存。如何改进我的代码?

感谢 Karl Anderson 对代码的帮助。

4

1 回答 1

2

我很抱歉没有早点注意到这一点,但我早先给了你不正确的逻辑。

更好的解决方案是使用 a 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" />
于 2013-08-21T00:57:13.443 回答