2010-01-30 178 views
1

任何一個可以告訴我的代碼來驗證註冊表格的日期字段(SHD也驗證天的閏年,並沒有在每個月日期驗證

回答

2

這取決於輸入,但是假設你有整個日期的字符串輸入,那麼你可以嘗試這樣的:

try 
{ 
    DateTime parsedDate = DateTime.Parse(incomingDateString); 
} 
catch 
{ 
    throw new Exception("Incoming Date string could not be parsed as a DateTime"); 
} 

或者,如果你有三個整數從表格然後你會進來的字符串與

 DateTime parsedDate = new DateTime(Int32.Parse(yearString), Int32.Parse(MonthString), Int32.Parse(DayString)); 

更換DateTime.Parse並允許DateTime構造帶的分析的月份和閏年的天的細節。您可能會更復雜,並使用Int32.TryParse並提供更具體的錯誤消息和檢查空字符串,如果這就是你需要的。

+0

非常感謝很多朋友,非常感謝 – 2010-01-30 20:49:38

1

您可以確保您通過添加得到有效日期一個日曆控件或一個日期選擇器控件,這樣可以避免爲了驗證這個字段而添加額外的驗證

如果你不想使用日曆控件或日期選擇器,可以使用DateTime.Parse並放置它在Try,Catch塊內。

dateString = YourDateField.Text; 
     try { 
     dateValue = DateTime.Parse(dateString); 
     } 
     catch (FormatException) { 
     Console.WriteLine("Unable to convert, this is not a valid date '{0}'.", dateString); 
     } 

希望這h ELPS。

+0

非常感謝很多朋友,非常感謝 – 2010-01-30 20:48:42