[英]Date is invalid in Chrome with ISO format - tested with: 2012-11-31
谁来回答我的问题?
如何使用Javascript跨浏览器验证日期?
我使用无效日期:2011-11-31如下:
var d = new Date("2012-11-31")
d = NaN // Date is invalid
d.getFullYear();//2012
d.getDate();//1
d.getMonth();//11
测试过IE7-9,chrome,opera,safari,firefox。 在这里测试: http : //jsfiddle.net/MRwAq/
你可以这样做:
(function(){
//This should be good enough initial filter, let the native Date decide if the number are valid
var validStringRE = /^([0-9]{4})-([0-1][0-9])-([0-3][0-9])$/;
function pad( num ) {
return num < 10 ? "0"+num : num;
}
Date.prototype.getISOFormat = function(){
return this.getFullYear() + "-" +
pad( ( this.getMonth() + 1 ) ) + "-" +
pad( this.getDate() );
};
function isValidISODate( date ) {
var matches, a;
if( !validStringRE.test( date.toString() ) ) {
return false; //Get rid of anything but "NNNN-NN-NN"
}
matches = date.match( validStringRE );
a = new Date( +matches[1], +matches[2] - 1, +matches[3], 0, 0, 0, 0 );
if( isNaN( a ) ) {
return false; //firefox, ie
}
if( a.toString().toLowerCase() === "invalid date" ) {
return false; //chrome in some cases, opera, safari
}
return a.getISOFormat() === date; //browsers that "conveniently" calculate
}
window.isValidISODate = isValidISODate;
})()
然后:
var isValid = isValidISODate("2012-11-31");
//false
var isValid = isValidISODate("2012-11-30");
//true
您无法可靠地做到这一点。 见标准第15.9.4.2节:
该函数首先尝试根据日期时间字符串格式(15.9.1.15)中调出的规则来解析字符串的格式。 如果String不符合该格式,则该函数可以回退到任何特定于实现的启发式或特定于实现的日期格式。
基本上,如果你输入一个无效的日期,语言可以做任何你想做的事情,即回馈NaN
或尝试按其认为合适的方式“修复”它。
Esailija发布了一种实用的测试方法,似乎效果很好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.