如何编写正则表达式来验证日期? [英] How to write regex to validate dates?
本文介绍了如何编写正则表达式来验证日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用JavaScript,我需要弄清楚如何使用正则表达式确定有效日期。
I'm working in JavaScript and I need to figure out how to determine a valid date using regular expressions.
比赛将是:
dd-mm-yyyy
dd-mm-yy
此外,不应接受前导零,如:
Also, no leading zeros should be accepted like:
9-8-2010
10-6-99
如何编写正则表达式来执行此操作?
How can I write a regular expression to do this?
推荐答案
我想出了这个:
function isValidDate(inputDate){
var myRegex = /^(\d{1,2})([\-\/])(\d{1,2})\2(\d{4}|\d{2})$/;
var match = myRegex.exec(inputDate);
if (match != null) {
var auxDay = match[1];
var auxMonth = match[3] - 1;
var auxYear = match[4];
auxYear = auxYear.length < 3 ? (auxYear < 70 ? '20' + auxYear : '19' + auxYear) : auxYear;
var testingDate = new Date(auxYear,auxMonth,auxDay);
return ((auxDay == testingDate.getDate()) && (auxMonth == testingDate.getMonth()) && (auxYear == testingDate.getFullYear()));
} else return false;
}
适用于 dd-mm-yyyy
, dd-mm-yy
, dm-yyyy
和 dm-yy
,使用 -
或 /
作为分隔符
Works for dd-mm-yyyy
, dd-mm-yy
, d-m-yyyy
and d-m-yy
, using -
or /
as separators
基于此脚本
这篇关于如何编写正则表达式来验证日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文