Javascript 日期正则表达式 DD/MM/YYYY
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5465375/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript date regex DD/MM/YYYY
提问by Juan Ignacio
I know there are a lot of regex threads out there by I need a specific pattern I couldn't fin anywhere
我知道有很多正则表达式线程,因为我需要一个我在任何地方都找不到的特定模式
This regex validates in a YYYY-MM-DD format
此正则表达式以 YYYY-MM-DD 格式验证
/^\d{4}[\/\-](0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])$/
I need the pattern to be DD/MM/YYYY (day first since it's in spanish and only "/", "-" should not be allowed)
我需要模式为 DD/MM/YYYY(第一天,因为它是西班牙语,并且只允许“/”、“-”)
I searched several regex libraries and I think this one should work... but since I'm not familiar with regex I'm not sure it validates like that
我搜索了几个正则表达式库,我认为这个应该可以工作……但是因为我不熟悉正则表达式,所以我不确定它是否像那样验证
(0[1-9]|[12][0-9]|3[01])[ \.-](0[1-9]|1[012])[ \.-](19|20|)\d\d
I also don't know ho to escape the slashes, I try to "see" the logic in the string but it's like trying "see" the Matrix code for me. I'm placing the regex string in a options .js
我也不知道如何转义斜线,我尝试“查看”字符串中的逻辑,但这就像为我“查看”矩阵代码一样。我将正则表达式字符串放在 options .js 中
[...] },
"date": {
"regex": (0[1-9]|[12][0-9]|3[01])[ \.-](0[1-9]|1[012])[ \.-](19|20|)\d\d,
"alertText": "Alert text AAAA-MM-DD"
},
"other type..."[...]
So, if the regex is ok, how would I escape it? if it's not, what's the correct regex and how do I escape it? :P
所以,如果正则表达式没问题,我将如何逃避它?如果不是,正确的正则表达式是什么,我该如何逃避它?:P
Thanks a lot
非常感谢
回答by mVChr
You could take the regex that validates YYYY/MM/DD and flip it around to get what you need for DD/MM/YYYY:
您可以使用验证 YYYY/MM/DD 的正则表达式并将其翻转以获得 DD/MM/YYYY 所需的内容:
/^(0?[1-9]|[12][0-9]|3[01])[\/\-](0?[1-9]|1[012])[\/\-]\d{4}$/
BTW - this regex validates for either DD/MM/YYYY or DD-MM-YYYY
顺便说一句 - 此正则表达式验证 DD/MM/YYYY 或 DD-MM-YYYY
P.S. This will allow dates such as 31/02/4899
PS 这将允许诸如 31/02/4899 之类的日期
回答by OammieR
Take a look from here https://www.regextester.com/?fam=114662
从这里看一下https://www.regextester.com/?fam=114662
Use this following Regular Expression Details, This will support leap year also.
使用以下正则表达式详细信息,这也将支持闰年。
var reg = /^(((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])|(([1][26]|[2468][048]|[3579][26])00))))$/g;
回答by maerics
A regex is good for matching the general format but I think you should move parsing to the Date class, e.g.:
正则表达式适用于匹配通用格式,但我认为您应该将解析移至 Date 类,例如:
function parseDate(str) {
var m = str.match(/^(\d{1,2})\/(\d{1,2})\/(\d{4})$/);
return (m) ? new Date(m[3], m[2]-1, m[1]) : null;
}
Now you can use this function to check for valid dates; however, if you need to actually validate without rolling (e.g. "31/2/2010" doesn't automatically roll to "3/3/2010") then you've got another problem.
现在您可以使用此函数来检查有效日期;但是,如果您需要在不滚动的情况下进行实际验证(例如,“31/2/2010”不会自动滚动到“3/3/2010”),那么您还有另一个问题。
[Edit]If you also want to validate without rolling then you could add a check to compare against the original string to make sure it is the same date:
[编辑]如果您还想在不滚动的情况下进行验证,那么您可以添加一个检查以与原始字符串进行比较以确保它是相同的日期:
function parseDate(str) {
var m = str.match(/^(\d{1,2})\/(\d{1,2})\/(\d{4})$/)
, d = (m) ? new Date(m[3], m[2]-1, m[1]) : null
, nonRolling = (d&&(str==[d.getDate(),d.getMonth()+1,d.getFullYear()].join('/')));
return (nonRolling) ? d : null;
}
[Edit2]If you want to match against zero-padded dates (e.g. "08/08/2013") then you could do something like this:
[Edit2]如果您想匹配零填充日期(例如“08/08/2013”),那么您可以执行以下操作:
function parseDate(str) {
function pad(x){return (((''+x).length==2) ? '' : '0') + x; }
var m = str.match(/^(\d{1,2})\/(\d{1,2})\/(\d{4})$/)
, d = (m) ? new Date(m[3], m[2]-1, m[1]) : null
, matchesPadded = (d&&(str==[pad(d.getDate()),pad(d.getMonth()+1),d.getFullYear()].join('/')))
, matchesNonPadded = (d&&(str==[d.getDate(),d.getMonth()+1,d.getFullYear()].join('/')));
return (matchesPadded || matchesNonPadded) ? d : null;
}
However, it will still fail for inconsistently padded dates (e.g. "8/08/2013").
但是,对于填充不一致的日期(例如“8/08/2013”),它仍然会失败。
回答by Pau
Scape slashes is simply use \
before /
and it will be escaped. (\/
=> /
).
Scape 斜线只是\
在之前使用/
,它将被转义。( \/
=> /
)。
Otherwise you're regex DD/MM/YYYY could be next:
否则你是正则表达式 DD/MM/YYYY 可能是下一个:
/^[0-9]{2}[\/]{1}[0-9]{2}[\/]{1}[0-9]{4}$/g
/^[0-9]{2}[\/]{1}[0-9]{2}[\/]{1}[0-9]{4}$/g
Explanation:
解释:
[0-9]
: Just Numbers{2}
or{4}
: Length 2 or 4. You could do{2,4}
as well to length between two numbers (2 and 4 in this case)[\/]
: Character/
g
: Global -- Orm
: Multiline (Optional, see your requirements)$
: Anchor to end of string. (Optional, see your requirements)^
: Start of string. (Optional, see your requirements)
[0-9]
: 只是数字{2}
或{4}
: 长度 2 或 4。您也可以{2,4}
在两个数字之间设置长度(在本例中为 2 和 4)[\/]
: 特点/
g
: Global -- 或m
: Multiline(可选,请参阅您的要求)$
: 锚定到字符串的末尾。(可选,见您的要求)^
: 字符串的开始。(可选,见您的要求)
An example of use:
使用示例:
var regex = /^[0-9]{2}[\/][0-9]{2}[\/][0-9]{4}$/g;
var dates = ["2009-10-09", "2009.10.09", "2009/10/09", "200910-09", "1990/10/09",
"2016/0/09", "2017/10/09", "2016/09/09", "20/09/2016", "21/09/2016", "22/09/2016",
"23/09/2016", "19/09/2016", "18/09/2016", "25/09/2016", "21/09/2018"];
//Iterate array
dates.forEach(
function(date){
console.log(date + " matches with regex?");
console.log(regex.test(date));
});
Of course you can use as boolean:
当然,您可以使用布尔值:
if(regex.test(date)){
//do something
}
回答by edid
I use this function for dd/mm/yyyy format :
我将此函数用于 dd/mm/yyyy 格式:
// (new Date()).fromString("3/9/2013") : 3 of september
// (new Date()).fromString("3/9/2013", false) : 9 of march
Date.prototype.fromString = function(str, ddmmyyyy) {
var m = str.match(/(\d+)(-|\/)(\d+)(?:-|\/)(?:(\d+)\s+(\d+):(\d+)(?::(\d+))?(?:\.(\d+))?)?/);
if(m[2] == "/"){
if(ddmmyyyy === false)
return new Date(+m[4], +m[1] - 1, +m[3], m[5] ? +m[5] : 0, m[6] ? +m[6] : 0, m[7] ? +m[7] : 0, m[8] ? +m[8] * 100 : 0);
return new Date(+m[4], +m[3] - 1, +m[1], m[5] ? +m[5] : 0, m[6] ? +m[6] : 0, m[7] ? +m[7] : 0, m[8] ? +m[8] * 100 : 0);
}
return new Date(+m[1], +m[3] - 1, +m[4], m[5] ? +m[5] : 0, m[6] ? +m[6] : 0, m[7] ? +m[7] : 0, m[8] ? +m[8] * 100 : 0);
}
回答by bkaancelen
Try using this..
尝试使用这个..
[0-9]{2}[/][0-9]{2}[/][0-9]{4}$
this should work with this pattern DD/DD/DDDD
where D is any digit (0-9)
这应该适用于这种模式DD/DD/DDDD
,其中 D 是任何数字 (0-9)
回答by user1693371
((?=\d{4})\d{4}|(?=[a-zA-Z]{3})[a-zA-Z]{3}|\d{2})((?=\/)\/|\-)((?=[0-9]{2})[0-9]{2}|(?=[0-9]{1,2})[0-9]{1,2}|[a-zA-Z]{3})((?=\/)\/|\-)((?=[0-9]{4})[0-9]{4}|(?=[0-9]{2})[0-9]{2}|[a-zA-Z]{3})
Regex Compile on it
正则表达式编译就可以了
2012/22/Jan
2012/22/12
2012/22/12
2012/22/12
2012/22/12
2012/22/12
2012/22/12
2012-Dec-22
2012-12-22
23/12/2012
23/12/2012
Dec-22-2012
12-2-2012
23-12-2012
23-12-2012
回答by Anjana Silva
For people who needs to validate years earlier than year 1900, following should do the trick. Actually this is same as the above answer given by [@OammieR][1]
BUT with years including 1800 - 1899.
对于需要验证早于 1900 年的人,以下应该可以解决问题。实际上这与[@OammieR][1]
BUT给出的上述答案相同,年份包括 1800 - 1899。
/^(((0[1-9]|[12]\d|3[01])\/(0[13578]|1[02])\/((19|[2-9]\d)\d{2}))|((0[1-9]|[12]\d|3[01])\/(0[13578]|1[02])\/((18|[2-9]\d)\d{2}))|((0[1-9]|[12]\d|30)\/(0[13456789]|1[012])\/((19|[2-9]\d)\d{2}))|((0[1-9]|[12]\d|30)\/(0[13456789]|1[012])\/((18|[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))))$/
Hope this helps someone who needs to validate years earlier than 1900, such as 01/01/1855
, etc.
希望这可以帮助那些需要验证早于 1900 年的人,例如01/01/1855
,等等。
Thanks @OammieR
for the initial idea.
感谢@OammieR
您的最初想法。
回答by Naraen
If you are in Javascript already, couldn't you just use Date.Parse() to validate a date instead of using regEx.
如果您已经在使用 Javascript,难道您不能只使用 Date.Parse() 来验证日期而不是使用 regEx。
RegEx for date is actually unwieldy and hard to get right especially with leap years and all.
日期的正则表达式实际上很笨拙且难以正确,尤其是在闰年之类的情况下。
回答by Jayesh Bhalodia
Do the following change to the jquery.validationengine-en.js
file and update the dd/mm/yyyy inline validation by including leap year:
对jquery.validationengine-en.js
文件进行以下更改并通过包含闰年更新 dd/mm/yyyy 内联验证:
"date": {
// Check if date is valid by leap year
"func": function (field) {
//var pattern = new RegExp(/^(\d{4})[\/\-\.](0?[1-9]|1[012])[\/\-\.](0?[1-9]|[12][0-9]|3[01])$/);
var pattern = new RegExp(/^(0?[1-9]|[12][0-9]|3[01])[\/\-\.](0?[1-9]|1[012])[\/\-\.](\d{4})$/);
var match = pattern.exec(field.val());
if (match == null)
return false;
//var year = match[1];
//var month = match[2]*1;
//var day = match[3]*1;
var year = match[3];
var month = match[2]*1;
var day = match[1]*1;
var date = new Date(year, month - 1, day); // because months starts from 0.
return (date.getFullYear() == year && date.getMonth() == (month - 1) && date.getDate() == day);
},
"alertText": "* Invalid date, must be in DD-MM-YYYY format"