2010-01-30 143 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