Visual Studio / Visual Basic文本框仅接收格式化日期

时间:2013-10-11 23:26:43

标签: vb.net date visual-studio-2012 format

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

我确实知道有内置函数,但在这种情况下我不允许使用它们。

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

1 个答案:

答案 0 :(得分: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,当你阅读它时似乎更有意义。