Javascript:如何验证 MM-DD-YYYY 格式的日期? [英] Javascript: how to validate dates in format MM-DD-YYYY?
本文介绍了Javascript:如何验证 MM-DD-YYYY 格式的日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在这里看到了一个可能的答案,但那是针对 YYYY-MM-DD:JavaScript 日期验证
I saw a potential answer here but that was for YYYY-MM-DD: JavaScript date validation
我像这样修改了上面的 MM-DD-YYYY 代码代码,但我仍然无法让它工作:
I modified the code code above for MM-DD-YYYY like so but I still can't get it to work:
String.prototype.isValidDate = function()
{
var IsoDateRe = new RegExp("^([0-9]{2})-([0-9]{2})-([0-9]{4})$");
var matches = IsoDateRe.exec(this);
if (!matches) return false;
var composedDate = new Date(matches[3], (matches[1] - 1), matches[2]);
return ((composedDate.getMonth() == (matches[1] - 1)) &&
(composedDate.getDate() == matches[2]) &&
(composedDate.getFullYear() == matches[3]));
}
如何使上述代码适用于 MM-DD-YYYY 和更好的 MM/DD/YYYY?
How can I get the above code to work for MM-DD-YYYY and better yet MM/DD/YYYY?
谢谢.
推荐答案
function isValidDate(date)
{
var matches = /^(d{1,2})[-/](d{1,2})[-/](d{4})$/.exec(date);
if (matches == null) return false;
var d = matches[2];
var m = matches[1] - 1;
var y = matches[3];
var composedDate = new Date(y, m, d);
return composedDate.getDate() == d &&
composedDate.getMonth() == m &&
composedDate.getFullYear() == y;
}
console.log(isValidDate('10-12-1961'));
console.log(isValidDate('12/11/1961'));
console.log(isValidDate('02-11-1961'));
console.log(isValidDate('12/01/1961'));
console.log(isValidDate('13-11-1961'));
console.log(isValidDate('11-31-1961'));
console.log(isValidDate('11-31-1061'));
它有效.(用 Firebug 测试,因此是 console.log().)
It works. (Tested with Firebug, hence the console.log().)
这篇关于Javascript:如何验证 MM-DD-YYYY 格式的日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文