简体   繁体   中英

Date Validation - Only enter dates within current month

I've been assigned the task of validating a date field that gets populated when creating an invoice. It is a text box with three button objects that allow a user to select a date from a calendar, enter today's date, or remove the date entry.

My task is to make sure that users cannot enter a date that is NOT within the current month (double negative...tricky). My task is to make sure that users can only enter dates within the current month. (better?)

I have no idea how to do this. Should I use the asp controls or do this on the back end?

I'm using VB.NET.

Use the ASP.NET Validator controls, like this:

Markup:

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

Note: I have included the RequireFieldValidator to ensure that we have a value to compare against for the date validation.

Code-behind ( Page_Load ):

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

Code-behind (utility function):

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

Note: I included a function to determine the date for the first day of the current month. The Page_Load is calling that function and then passing that to the validator as the value to compare for less than.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM