【问题标题】:How to validate if a textbox is in the correct date format?如何验证文本框的日期格式是否正确?
【发布时间】:2019-01-24 17:18:36
【问题描述】:

我有一个用户窗体,如果用户在文本框中输入dd/mm/yyyy 以外的日期格式,则单击提交按钮后会弹出错误消息。这是我到目前为止所拥有的,它仅将无效的日期输入格式化为 dd/mm/yyyy,但不显示验证:

If IsDate(Me.DOBTextBox.Value) Then
    Me.DOBTextBox = Format(Me.DOBTextBox.Value, "dd/mm/yyyy")

ElseIf Not IsDate(Me.DOBTextBox.Value) Then
    MsgBox "Please enter a valid date format dd/mm/yyyy", vbCritical
    DOBTextBox.SetFocus
    Exit Sub
End If

【问题讨论】:

  • 你会检查 dd 是否为 32 吗?
  • 这是一个有趣的link
  • 嗨 @SolarMike 你的意思是输入 dd 为 32 吗?
  • @JvdV 我试过这个自定义日历,但我发现它对我来说有点复杂。

标签: excel vba


【解决方案1】:

验证其中是否有 2 个斜杠 / 和 day <= 31 和 month <= 12:

Dim ArrInput As Variant
ArrInput = Split(Me.DOBTextBox.Value, "/")

Dim ValidDate As Boolean

If UBound(ArrInput) = 2 Then 'make sure there are exactly two slashes in the date
    If ArrInput(1) > 0 And ArrInput(1) <= 12 And _
    ArrInput(0) > 0 And ArrInput(0) <= 31 Then     'month <=12 & day <= 31
        ValidDate = True
    End If
Else
    ValidDate = False
End If

If Not ValidDate Then
    MsgBox "Please enter a valid date format dd/mm/yyyy", vbCritical
    DOBTextBox.SetFocus
    Exit Sub
End If

'code here that executes when date is valid
Dim MyValidDate As Date
MyValidDate = DateSerial(ArrInput(2), ArrInput(1), ArrInput(0))

或者只是尝试将字符串日期转换为真实日期并检查day、month 和year 是否与字符串中的值匹配。

Dim ArrInput As Variant
ArrInput = Split(Me.DOBTextBox.Value, "/")

Dim ValidDate As Boolean

If UBound(ArrInput) = 2 Then 'make sure there are exactly two slashes in the date
    Dim MyValidDate As Date
    MyValidDate = DateSerial(ArrInput(2), ArrInput(1), ArrInput(0))

    If Day(MyValidDate) = CLng(ArrInput(0)) And _
       Month(MyValidDate) = CLng(ArrInput(1)) And _
       Year(MyValidDate) = CLng(ArrInput(2)) Then
        ValidDate = True
    End If
End If

If Not ValidDate Then
    MsgBox "Please enter a valid date format dd/mm/yyyy", vbCritical
    'DOBTextBox.SetFocus
    Exit Sub
End If

'code here that executes when date is valid
MsgBox "date is valid " & MyValidDate

【讨论】:

  • 你好@Peh,只是想知道。如果用户习惯于输入 mm/dd/yyyy 并输入日期 02/03/2019,这里会发生什么。他显然想说 2 月 3 日,但这里的 OP 将在 3 月 2 日开始。我的假设正确吗?
  • 嗯,除了使用不能被误解的日期格式(如 ISO 8601 格式 YYYY-MM-DD (我强烈建议使用))之外,您无法阻止这种情况。 • 我的意思是,如果您告诉用户输入dd/mm/yyyy 而他输入错误,您就无法阻止它。这就是YYYY-MM-DD 如此强大的原因。如果输入为字符串,它是唯一不会被误解的日期格式。 • 您只需验证格式。您无法验证用户是否输入了正确的日期(只要它是根据格式的有效日期)。
  • 您是对的,感谢您的快速回复。使 OP 在这里尝试做的事情容易出现错误的输入 imo。我知道这不是就此进行深入讨论的地方,但是使用日期选择器可以消除错误,或者如果您必须使用文本框,为什么不使用三个(日、月和年)。
  • 这就像用户实际上想要输入02/03/2019 但实际上意外地输入03/03/2019 一样(日期选择器或其他东西不会阻止这种情况)。日期选择器或 3 个文本框的缺点是您无法复制/粘贴日期。作为淘汰赛(至少对我而言)。 • 我倾向于强迫用户多思考。如果他们输入了错误的日期,他们就输入了错误的日期。他们会注意到与否。我们不能强迫他们做对。
  • 嗨@Pᴇʜ感谢这个决议!但是我注意到这段代码没有考虑到某些月份的不同天数。 (1 月 31 天、2 月 29 天、4 月 30 天等)当我单击提交按钮时,它接受无效日期(30/02/2019)我一直在努力解决,你有什么想法吗?
猜你喜欢
  • 2012-08-05
  • 1970-01-01
  • 2011-11-07
  • 2011-06-29
  • 1970-01-01
  • 1970-01-01
  • 2013-01-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多