0

i need to create some code, that will do the following. The user inputs only numbers, which i have coded with the key press event. Next is the length of the date can only be 8 characters long. mm/dd/yy Also inside this condition i need to have the month, day and year be stored in different variables so that i can validate individually if the correct date for each month, day, and year are correct. for instance we don't have more than 12 months in a year. So i was thinking about using substring to pull apart the one variable that holds the input of the textbox then validate individually.

I do realize that there is built-in functions but in this case i am not allowed to use them.

Private Sub btnCheckDate_Click(sender As Object, e As EventArgs) Handles btnCheckDate.Click

Dim strDate As String
Dim badDate As Boolean = False

    strDate = txtInput.TabIndex
    If strDate.Length <> 8 Then
        MessageBox.Show("Bad date")
        txtInput.Text = String.Empty
        txtInput.Focus()
    End If

    Dim intMonth As Integer
    Dim intDay As Integer
    Dim intYear As Integer

    intMonth = CInt(strDate.Substring(0, 2)) 
4

1 回答 1

0

我假设当你说你不能使用内置函数时,你的意思是日期/时间函数。这是验证文本并将每个部分放入变量的一种简单方法:

Dim strDate As String = txtInput.Text
Dim intMonth As Integer
Dim intDay As Integer
Dim intYear As Integer
Dim badDate As Boolean = True
If strDate.Length = 8 Then
    Dim DateParts As List(Of String) = txtInput.Text.Split("/"c).ToList
    If DateParts.Count = 3 Then
        If Integer.TryParse(DateParts(0), intMonth) AndAlso Integer.TryParse(DateParts(1), intDay) AndAlso Integer.TryParse(DateParts(2), intYear) Then
            If intMonth <= 12 AndAlso intDay <= 31 AndAlso intYear <= 20 Then
                badDate = False
            End If
        End If
    End If
End If
If badDate = True Then
    MessageBox.Show("Bad date")
    txtInput.Text = String.Empty
    txtInput.Focus()
End If

还有其他验证可以在不同长度的月份和闰年中完成。只需添加更多条件语句。

我将 badDate 更改为默认为 True,当您阅读它时似乎更有意义。

于 2013-10-13T23:19:08.150 回答