Javascript:如何验证MM-DD-YYYY格式的日期? [英] Javascript: how to validate dates in format MM-DD-YYYY?
本文介绍了Javascript:如何验证MM-DD-YYYY格式的日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在这里看到了一个潜在的答案,但是对于YYYY-MM-DD来说:
I saw a potential answer here but that was for YYYY-MM-DD: JavaScript date validation
:
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屋!
查看全文