2013-08-26 43 views
4

我需要驗證的日期格式,即可以是11/11/1111/22/2013,即一年塊可以在YYYYYY和完整格式要麼MM/DD/YYMM/DD/YYYY正則表達式來檢查長度與多個選項

我有這個代碼

^(\d{1,2})\/(\d{1,2})\/(\d{4})$ 

,我已經試過

^(\d{1,2})\/(\d{1,2})\/(\d{2}{4})$ // doesn't works, does nothing 

^(\d{1,2})\/(\d{1,2})\/(\d{2|4})$ // and it returns null every time 

PS:我使用Javascript/jQuery的應用它

回答

8
^(\d{1,2})\/(\d{1,2})\/(\d{2}|\d{4})$ 

兩個\d{2}{4}\d{2|4}是不正確的正則表達式表達。你所要做的兩位數爲數字單獨和組合,然後利用(\d{2}|\d{4})

+0

優秀( Y).. – zzlalani

+0

@zzlalani這不是驗證日期,如48/66/5432? –

+0

@Sniffer是的,它會的。但我認爲這不是問題的一部分。但是,是的,我不會**我們的代碼來驗證任何應用程序中的任何日期字段。 – MarcinJuraszek

2

你可以使用:

^\d\d?/\d\d?/\d\d(?:\d\d)?$ 

解釋:

The regular expression: 

(?-imsx:^\d\d?/\d\d?/\d\d(?:\d\d)?$) 

matches as follows: 

NODE      EXPLANATION 
---------------------------------------------------------------------- 
(?-imsx:     group, but do not capture (case-sensitive) 
         (with^and $ matching normally) (with . not 
         matching \n) (matching whitespace and # 
         normally): 
---------------------------------------------------------------------- 
^      the beginning of the string 
---------------------------------------------------------------------- 
    \d      digits (0-9) 
---------------------------------------------------------------------- 
    \d?      digits (0-9) (optional (matching the most 
          amount possible)) 
---------------------------------------------------------------------- 
/      '/' 
---------------------------------------------------------------------- 
    \d      digits (0-9) 
---------------------------------------------------------------------- 
    \d?      digits (0-9) (optional (matching the most 
          amount possible)) 
---------------------------------------------------------------------- 
/      '/' 
---------------------------------------------------------------------- 
    \d      digits (0-9) 
---------------------------------------------------------------------- 
    \d      digits (0-9) 
---------------------------------------------------------------------- 
    (?:      group, but do not capture (optional 
          (matching the most amount possible)): 
---------------------------------------------------------------------- 
    \d      digits (0-9) 
---------------------------------------------------------------------- 
    \d      digits (0-9) 
---------------------------------------------------------------------- 
)?      end of grouping 
---------------------------------------------------------------------- 
    $      before an optional \n, and the end of the 
          string 
---------------------------------------------------------------------- 
)      end of grouping 
----------------------------------------------------------------------