如何让JavaScript遇到无效日期输入时抛出错误而非自动校正
解决方案
原生Date的设计默认会自动修正无效日期值,没有内置开关可以直接关闭该行为,你可以通过以下两种方式实现严格校验,遇到无效日期直接抛出错误:
方案一:自定义严格日期解析函数(最推荐,无全局污染)
仅在你需要严格校验的场景调用该函数即可,不会影响其他代码的Date使用逻辑:
/** * 严格解析YYYY-MM-DD格式的日期,无效日期直接抛出错误 * @param {string} dateStr 待解析的日期字符串 * @returns {Date} 解析后的合法Date实例 */ function parseStrictISODate(dateStr) { // 可根据你的实际输入格式调整正则规则 const dateRegex = /^(\d{4})-(\d{2})-(\d{2})$/; const matchResult = dateStr.match(dateRegex); if (!matchResult) { throw new Error(`日期格式非法:${dateStr},请使用YYYY-MM-DD格式`); } const inputYear = parseInt(matchResult[1], 10); // 注意JS月份从0开始计数 const inputMonth = parseInt(matchResult[2], 10) - 1; const inputDay = parseInt(matchResult[3], 10); const parsedDate = new Date(inputYear, inputMonth, inputDay); // 校验解析后的日期是否和输入参数完全一致,避免自动修正 if ( parsedDate.getFullYear() !== inputYear || parsedDate.getMonth() !== inputMonth || parsedDate.getDate() !== inputDay ) { throw new Error(`日期值非法:${dateStr} 不存在`); } return parsedDate; } // 测试示例 console.log(parseStrictISODate("2000-02-29")); // 正常返回日期实例 console.log(parseStrictISODate("2000-02-31")); // 抛出错误:日期值非法:2000-02-31 不存在
方案二:重写全局Date构造函数(不推荐,副作用极大)
如果确定全局所有Date调用都需要严格校验,可以 monkey patch 原生Date,该改动会影响所有依赖Date的代码,谨慎使用:
// 保存原生Date构造函数 const NativeDate = Date; Date = function(...args) { // 处理非new调用的场景:Date()直接返回时间字符串 if (!new.target) { return NativeDate.apply(this, args); } // 仅对单个字符串类型的入参做严格校验,其他入参场景可自行扩展 if (args.length === 1 && typeof args[0] === 'string') { const dateRegex = /^(\d{4})-(\d{2})-(\d{2})$/; const matchResult = args[0].match(dateRegex); if (matchResult) { const inputYear = parseInt(matchResult[1], 10); const inputMonth = parseInt(matchResult[2], 10) - 1; const inputDay = parseInt(matchResult[3], 10); const tempDate = new NativeDate(inputYear, inputMonth, inputDay); if ( tempDate.getFullYear() !== inputYear || tempDate.getMonth() !== inputMonth || tempDate.getDate() !== inputDay ) { throw new Error(`日期值非法:${args[0]} 不存在`); } } } // 其他场景正常调用原生构造逻辑 return new NativeDate(...args); }; // 继承原生Date的静态方法和原型,避免原有功能失效 Date.prototype = NativeDate.prototype; Date.now = NativeDate.now; Date.parse = NativeDate.parse; Date.UTC = NativeDate.UTC; // 测试示例 console.log(new Date("2000-02-31")); // 直接抛出错误
注意事项
如果需要支持带时分秒的日期格式,只需调整正则匹配规则,额外校验时分秒的数值是否在合法范围内即可。
内容的提问来源于stack exchange,提问作者Bear Bile Farming is Torture
相关产品推荐
相关产品推荐

