我正在处理发票的日期字段。为发票日期选择的日期不能是当月之外的任何一天。
这是我的代码:
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致信,以获得有关代码的帮助。
答案 0 :(得分: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" />