2012-06-01 34 views
3

我有一個正則表達式的有效日期是如下我如何驗證日期以不同的格式

^(((0[1-9]|[12]\d|3[01])\/(0[13578]|1[02])\/((19|[2-9]\d)\d{2}))|((0[1-9]|[12]\d|30)\/(0[13456789]|1[012])\/((19|[2-9]\d)\d{2}))|((0[1-9]|1\d|2[0-8])\/02\/((19|[2-9]\d)\d{2}))|(29\/02\/((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))))$

但是,這將有效的,如果我輸入如下20/03/2012日期。隨着同我想補充不同的驗證,可以爲下一起工作

20032012 (ddmmyyyy)03202012(mmddyyyy)

有人能幫助我

+0

1.作業錯誤的工具。使用自定義驗證邏輯或Compare/RangeValidator。 2.你無法解析* mm/dd和dd/mm,否則你如何確定05/04是5月4日還是4月5日? – mellamokb

+0

使用自定義驗證器並使用不同的正則表達式來驗證日期。 –

回答

12

使用DateTime.TryParseExact - 有一個重載需要一個格式字符串數組,因此您可以提供所有可能的格式。

從MSDN - DateTime.TryParseExact Method (String, String[], IFormatProvider, DateTimeStyles, DateTime)

string[] formats= {"M/d/yyyy h:mm:ss tt", "M/d/yyyy h:mm tt", 
        "MM/dd/yyyy hh:mm:ss", "M/d/yyyy h:mm:ss", 
        "M/d/yyyy hh:mm tt", "M/d/yyyy hh tt", 
        "M/d/yyyy h:mm", "M/d/yyyy h:mm", 
        "MM/dd/yyyy hh:mm", "M/dd/yyyy hh:mm"}; 
string[] dateStrings = {"5/1/2009 6:32 PM", "05/01/2009 6:32:05 PM", 
         "5/1/2009 6:32:00", "05/01/2009 06:32", 
         "05/01/2009 06:32:00 PM", "05/01/2009 06:32:00"}; 
DateTime dateValue; 

foreach (string dateString in dateStrings) 
{ 
    if (DateTime.TryParseExact(dateString, formats, 
           new CultureInfo("en-US"), 
           DateTimeStyles.None, 
           out dateValue)) 
     Console.WriteLine("Converted '{0}' to {1}.", dateString, dateValue); 
    else 
     Console.WriteLine("Unable to convert '{0}' to a date.", dateString); 
} 
// The example displays the following output: 
//  Converted '5/1/2009 6:32 PM' to 5/1/2009 6:32:00 PM. 
//  Converted '05/01/2009 6:32:05 PM' to 5/1/2009 6:32:05 PM. 
//  Converted '5/1/2009 6:32:00' to 5/1/2009 6:32:00 AM. 
//  Converted '05/01/2009 06:32' to 5/1/2009 6:32:00 AM. 
//  Converted '05/01/2009 06:32:00 PM' to 5/1/2009 6:32:00 PM. 
//  Converted '05/01/2009 06:32:00' to 5/1/2009 6:32:00 AM. 
+0

如何解析mm/dd和dd/mm,例如05/04會不明確? – mellamokb

+0

YOu不能。這是ASIMPLE。 05/04不能在沒有上下文的情況下自動解析。例如,基本上oyu必須知道區域是英語還是geran。簡單點 - 使用標準瀏覽器機制與用戶協商(如果是asp.net)。如果這是一個文件,那麼有人做了一個指定格式的垃圾作業。 – TomTom

+0

@TomTom:同意。這是OP在他們的問題中所要求的...... – mellamokb