2013-08-26 106 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 
----------------------------------------------------------------------