2014-12-19 67 views
1

嗨,我想通過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> DateTime.Now.ToString( 「MM/DD/YYYY」 )然後

+4

不做文字比較上最新數據。 https://dotnetfiddle.net/czRPsJ – Plutonix

+1

你爲什麼不分析日期字符串? –

+0

@Plutonix除非它是ISO 8601(http://en.wikipedia.org/wiki/ISO_8601)格式,並且日期介於[1000和10000之間)。 –

回答

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 
+0

謝謝我最終修復它 –

+0

謝謝。這是做到這一點的正確方法。 –

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 
+2

不要使用字符串來比較數據數據。 'txtPickupDate.Text <今天'會失敗的「1/31/2015」Pickupdate相比,說,#12/18/2014# – Plutonix

+0

@Plutonix你是對的 –