日期验证 - 仅在当月内输入日期

时间:2013-08-20 18:03:06

标签: javascript vb.net

我被分配了验证创建发票时填充的日期字段的任务。它是一个带有三个按钮对象的文本框,允许用户从日历中选择日期,输入今天的日期或删除日期条目。

我的任务是确保用户无法输入不在当月内的日期(双重否定......棘手)。 我的任务是确保用户只能输入当月的日期。 (更好?)

我不知道该怎么做。我应该使用asp控件还是在后端执行此操作?

我正在使用VB.NET。

1 个答案:

答案 0 :(得分:2)

使用ASP.NET Validator控件,如下所示:

标记:

<asp:TextBox id="YourTextBox" runat="server" />

<asp:RequiredFieldValidator ControlToValidate="YourTextBox" 
    Text="The date field is required!" runat="server" />
<asp:CompareValidator ID="compareValidatorDate" ControlToValidate="YourTextBox" 
    Type="Date" Operator="LessThan" ErrorMessage="Date must be from this month!"
    Display="Dynamic" runat="server" />

注意:我已添加RequireFieldValidator以确保我们有一个值可与日期验证进行比较。

代码隐藏(Page_Load):

If Not IsPostBack Then
    Dim firstOfTheMonthDate As DateTime = FirstDayOfMonthFromDateTime(DateTime.Now)
    Me.compareValidatorDate.ValueToCompare = firstOfTheMonthDate.ToString("d")
End If

代码隐藏(效用函数):

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

注意:我添加了一个函数来确定当月第一天的日期。 Page_Load正在调用该函数,然后将其传递给验证器作为要比较的值小于。