2013-10-11 77 views
0

我需要創建一些代碼,這將執行以下操作。用戶只輸入我用密鑰按下事件編碼的數字。接下來是日期的長度只能是8個字符長。 mm/dd/yy同樣在這種情況下,我需要將月份,日期和年份存儲在不同的變量中,以便我可以單獨驗證每個月,每天和每年的正確日期是否正確。比如我們一年的時間不超過12個月。所以我正在考慮使用子字符串來分開保存文本框輸入的一個變量,然後單獨驗證。Visual Studio/Visual Basic文本框只接收格式化日期

我知道有內置函數,但在這種情況下,我不允許使用它們。

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

改爲使用'Date.ParseExact(strDate,「MM/dd/yy」,CultureInfo.InvariantCulture)''。您可以使用具有相同格式的'Date.TryParseExact'來驗證輸入。 –

+0

你是什麼意思「我不允許使用內置函數」? 'Substring'是一個「內置函數」(就像'Date.Parse'或者其他任何你想調用的方法一樣)。 – pescolino

+0

我認爲這意味着日期驗證功能。使用子字符串將其切分,轉換爲int,然後驗證每個值。我會額外獲得信貸,並允許8或10個字符(MM/DD/YYYY),因爲它只會改變您如何收取年度價值。額外的額外功勞,使每個驗證一個被調用的函數返回T/F。提示:先做月份。 – Plutonix

回答

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,當您閱讀它時似乎更有意義。