Visual Studio/Visual Basic Textbox 仅接收格式化日期



我需要创建一些代码,这将执行以下操作。用户只输入数字,我已经用按键事件对其进行了编码。接下来是日期的长度只能是8个字符长。月/日/年 同样在这种情况下,我需要将月、日和年存储在不同的变量中,以便我可以单独验证每个月、日和年的正确日期是否正确。例如,我们一年的时间不超过 12 个月。所以我正在考虑使用子字符串来拉开一个保存文本框输入的变量,然后单独验证。

确实意识到有内置功能,但在这种情况下,我不允许使用它们。

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)) 

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

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,当您阅读它时似乎更有意义。

最新更新