我在这里看到了一个潜在的答案,但那是YYYY-MM-DD:JavaScript日期验证
我为MM-DD-YYYY修改了上面的代码,但我还是无法让它工作:
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?
谢谢.
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().)
function isValidDate(date) { var valid = true; date = date.replace('/-/g', ''); var month = parseInt(date.substring(0, 2),10); var day = parseInt(date.substring(2, 4),10); var year = parseInt(date.substring(4, 8),10); if(isNaN(month) || isNaN(day) || isNaN(year)) return false; if((month < 1) || (month > 12)) valid = false; else if((day < 1) || (day > 31)) valid = false; else if(((month == 4) || (month == 6) || (month == 9) || (month == 11)) && (day > 30)) valid = false; else if((month == 2) && (((year % 400) == 0) || ((year % 4) == 0)) && ((year % 100) != 0) && (day > 29)) valid = false; else if((month == 2) && ((year % 100) == 0) && (day > 29)) valid = false; else if((month == 2) && (day > 28)) valid = false; return valid; }
这将检查每个月的有效天数和有效的闰年天数.
如何以"任何"日期格式验证日期?我一直在使用DateJS库并将其添加到现有表单中,以确保我按照我想要的方式格式化有效的日期和时间.用户甚至可以输入"现在"和"明天"等内容,并将其转换为有效日期.
这是dateJS库:http://www.datejs.com/
这是我写的一个jQuery技巧:http: //www.ssmedia.com/utilities/jquery/index.cfm/datejs.htm