我在验证日期方面遇到了问题,在我的代码中我使用了接受2012年日期的正则表达式,如果我将日期定为2013年,则表示“无效日期”。请在这方面帮助我。它应该接受任何年份..我的意思是从2000年到3000年的有效年份。 提前谢谢。
function checkDates(){
var sdate = "2013-01-02";
var edate = "2013-01-02";
if (!isValidDate(sdate)) {
alert("Report Start Date is Invalid!!");
return false;
}
if (!isValidDate(edate)) {
alert("Report End Date is Invalid!!");
return false;
}
return true;
}
function isValidDate(sText) {
var reDate = /(?:([0-9]{4}) [ -](0[1-9]|[12][0-9]|3[01])[ -]0[1-9]|1[012])/; // yy/mm/dd
return reDate.test(sText);
}
答案 0 :(得分:6)
你的正则表达式中有一个额外的空格和缺少括号(括号问题使其接受2012-aa-xx
日期:
/(?:([0-9]{4}) [ -](0[1-9]|[12][0-9]|3[01])[ -]0[1-9]|1[012])/
^ ^
-------------/-------------------------------/
所以:
([0-9]{4}[ -](0[1-9]|[12][0-9]|3[01])[ -](0[1-9]|1[012]))
答案 1 :(得分:1)
以下表达式也有效
/(?:19|20\d{2})\-(?:0[1-9]|1[0-2])\-(?:0[1-9]|[12][0-9]|3[01])/
谢谢, DHIRAJ