现在验证日期时间的日期

时间:2014-12-19 18:46:47

标签: asp.net vb.net

您好我正在尝试通过asp的文本框控件验证我。

我希望它能够证明它是空的,是今天还是将来的日期而不是过去,日期格式是正确的MM / DD / YYY。

我为此写了这段代码:

    If String.IsNullOrEmpty(txtPickupDate.Text) Then
        lblError.Text = lblError.Text & "<BR>You must enter in the field Pickup Date."
        lblError.Visible = True
        rtn = False
    Else

        If txtPickupDate.Text > DateTime.Now.ToString("MM/DD/YYYY") Then
            lblError.Text = lblError.Text & "<BR>You must enter in a valid date for Pickup."
            lblError.Visible = True
            rtn = False
        Else
            Dim Pickup As Date
            If Date.TryParseExact(txtPickupDate.Text.ToString(), "mm/dd/yyyy", _
                                  System.Globalization.CultureInfo.CurrentCulture, _
                                  Globalization.DateTimeStyles.None, Pickup) Then
            Else
                lblError.Text = lblError.Text & "<BR>You must enter the Pickup Date in the format of MM/DD/YYYY."
                lblError.Visible = True
                rtn = False
            End If
        End If
    End If

然而,它不适用于

  

如果txtPickupDate.Text&gt; DateTime.Now.ToString(&#34; MM / DD / YYYY&#34;)然后

2 个答案:

答案 0 :(得分:1)

试试这个。 它将验证是否输入了可解析日期,然后仅检查日期部分以确定它是否在过去,现在或将来。

Dim enteredDate As DateTime
If Not DateTime.TryParse(txtPickupDate.Text, enteredDate) Then
    ' Invalid date entered.
Else
    ' Valid date entered.
    ' Validate against the date part only.
    If enteredDate.Date < DateTime.Today Then
        ' Date is in the past.
    Else
        ' Date is today or in the future.
    End If
End If

答案 1 :(得分:0)

我最终这样做了:

    Dim Today As String = DateTime.Today.ToString("MM/dd/yyyy")

    'Due Date 
    If String.IsNullOrEmpty(txtPickupDate.Text) Then
        lblError.Text = lblError.Text & "<BR>You must enter in the field Pickup Date."
        lblError.Visible = True
        rtn = False
    Else

        If txtPickupDate.Text < Today Then
            lblError.Text = lblError.Text & "<BR>You must enter in a valid date for Pickup Date."
            lblError.Visible = True
            rtn = False
        Else
            Dim Pickup As Date
            If Date.TryParseExact(txtPickupDate.Text.ToString(), "MM/dd/yyyy", _
                                  System.Globalization.CultureInfo.CurrentCulture, _
                                  Globalization.DateTimeStyles.None, Pickup) Then
            Else
                lblError.Text = lblError.Text & "<BR>You must enter the Pickup Date in the format of MM/DD/YYYY."
                lblError.Visible = True
                rtn = False
            End If
        End If
    End If