如何使用正则表达式仅验证 dd.mm.yyyy 的日期格式



我正在使用正则表达式验证日期格式为 DD.MM.YYYY^(d{2}).d{2}.(d{4})$.

不幸的是,这在以下情况下不起作用。

02:02:200 -> still gives as valid date even though used  :
33.33.3333 -> still gives as validate even though there is no 33 date and month etc.

DD.MM.YYYY 的正确正则表达式是什么?

如果您需要检查某些内容,例如非闰年的 6 月 31 日(不存在(或 2 月 29 日,您将需要比简单的 RegExp 更复杂的东西:

const test1 = '02:02:200',
test2 = '33.33.3333',

validate = dateStr => {
const [dd, mm, yyyy] = dateStr.split('.'),
date = new Date(yyyy, +mm-1, dd)
return  date.getFullYear() == yyyy &&
date.getMonth() == mm-1 &&
date.getDate() == dd
}

console.log(test1, validate(test1))
console.log(test2, validate(test2))
console.log('21.06.1982', validate('21.06.1982'))
.as-console-wrapper{min-height:100%;}

为了能够使用正则表达式验证这一点,您必须根据月份、是否是闰年、是否在日历更改期间、跳过或添加某些日期来验证日期范围; 这取决于区域设置。

你最好使用一些日期库,并询问它是否可以将字符串解析为正确的日期。

请参阅此答案,例如如何使用Moment执行此操作.js https://stackoverflow.com/a/22184830/108804

最新更新