简体   繁体   English

Javascript正则表达式以验证日期

[英]Javascript Regular Expression to validate date

I am rather unfamiliar with regular expressions. 我不熟悉正则表达式。 I am trying to write a regular expression for mm.dd.yyyy, mm/dd/yyyy or mm-dd-yyyy. 我正在尝试为mm.dd.yyyy,mm / dd / yyyy或mm-dd-yyyy写一个正则表达式。 This is what I have so far, I am completely unsure if I am even close. 到目前为止,这是我所拥有的,我完全不确定自己是否接近。

^[0-9]{4}-(((0[13578]|(10|12))-(0[1-9]|[1-2][0-9]|3[0-1]))|(02-(0[1-9]|[1-2][0-9]))|((0[469]|11)-(0[1-9]|[1-2][0-9]|30)))$

Thanks 谢谢

/^\d{2}[.\/-]\d{2}[.\/-]\d{4}$/

jsFiddle . jsFiddle

Note that this will allow them to be mixed up, ie 01/02-2010 would be valid. 请注意,这将允许他们混淆,即01/02-2010将是有效的。 To stop this, write it out three times like so... 要停止此操作,请像这样写三遍...

/^(?:\d{2}\.\d{2}\.\d{4}|\d{2}\/\d{2}\/\d{4}|\d{2}-\d{2}-\d{4})$/

jsFiddle . jsFiddle

(or just check cwolves's wonderful answer .) (或只是检查狼人的绝妙答案 。)


Your question title says... 您的问题标题说...

Javascript Regular Expression to validate date Javascript正则表达式以验证日期

If you also need to extract the portions, wrap them with parenthesis ( () ) which will turn them into capturing groups. 如果还需要提取这些部分,请用括号( () )将其包裹起来,这会将它们变成捕获组。 They will be stored in members of the returned array if a successful match. 如果匹配成功,它们将存储在返回数组的成员中。

/^\d{2}([.\/-])\d{2}\1\d{4}$/

will match 01/01/2000 , 01.01.2000 , NOT 01/01.2000 将匹配01/01/200001.01.2000 ,而不是01/01.2000

/^(\d{2})([.\/-])(\d{2})\2(\d{4})$/

does the same while wrapping the three date parts. 在包装三个日期部分时也是如此。

I have seen some monster regular expressions to match actual dates- they would not match 04/31/yyyy, for instance, or 02-29-2011. 我已经看到一些怪物正则表达式来匹配实际日期-例如,它们将不匹配04/31 / yyyy或02-29-2011。

It is simpler to try to make a date from the input, and then check the input. 尝试从输入中确定日期,然后检查输入更简单。

function isvalid_mdy(s){
    var day, A= s.split(/\D+/).map(function(itm){
        return parseInt(itm, 10)
    });
    try{
        day= new Date(A[2], A[0]-1, A[1]);
        if(day.getMonth()+1== A[0] && day.getDate()== A[1]) return day;
        throw 'Bad Date Format';
    }
    catch(er){
        return NaN;
    }

}

var s1= '04/31/2011';
isvalid_mdy(s1)

/*  returned value: (Number)
NaN

*/ * /

In PHP I use named matches, so different formats are easy: 在PHP中,我使用命名匹配项,因此很容易使用不同的格式:

$format = 'y-m-d'; // or 'd-m-y' or 'd/m/y' etc
$regexp = '#^'.strtr(preg_quote($format), array('y' => '(?P<year>(?:1|2)\d{3})', 'm' => '(?P<month>\d\d?)', 'd' => '(?P<day>\d\d?)')).'$#';

but I don't think it's possible like that in JS. 但我认为在JS中不可能做到这一点。 Maybe named matches some other way... 也许命名匹配以其他方式...

edit 编辑
I tried this: 我尝试了这个:

'2004-8-29'.match(/^(\3\d{4})-(\2\d\d?)-(\1\d\d?)$/)

but I don't think that's it... (Notice the \\3, \\2 and \\1 before the actual captures/matches) 但我认为不是...(请在实际捕获/匹配之前注意\\ 3,\\ 2和\\ 1)

In order 1, 2, 3, it matches. 在顺序1、2、3中,它匹配。 In order 3, 2, 1, it doesn't. 在顺序3、2、1中则没有。 Not sure what the \\1 , \\2 and \\3 do =) 不知道\\1\\2\\3做什么=)

I don't like repeating the patterns once each for . 我不喜欢为每个重复一次模式. , - and / -/

Try something like the below: 尝试如下所示的方法:

^(\d{2})(\/|-|\.)(\d{2})\2(\d{4})$

Note the use of \\2 representing the second matching group which is the group of . 请注意, \\2代表第二个匹配组,即的组. , - or / . -/ This will make sure that whatever symbol was between mm and dd will be matched between dd and yyyy. 这将确保mm和dd之间的任何符号都将在dd和yyyy之间匹配。

An interesting trick is that you can use Date.parse() to do something along those lines: 一个有趣的技巧是,您可以使用Date.parse()沿着这些方向进行操作:

// 1303617600000
Date.parse('4/24/2011')

// 1303617600000
Date.parse('4-24-2011')

// 1303617600000
Date.parse('4.24.2011')

// NaN
Date.parse('4/32/2011')

// NaN
Date.parse('foo')

It's not perfectly strict. 这不是很严格。 For example, it will successfully parse 2/30/2011 as valid. 例如,它将成功解析2/30/2011为有效。 It's a good 99%-strict sanity test though. 不过,这是一项很好的99%严格完整性测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM