JavaScript 校验日期有效性:两种实用方案
作者:拾光时间:2026-10-29 14:18:04浏览:176
本文介绍两种在 JavaScript 中判断日期字符串是否有效的方法。第一种利用 Date 对象构造函数自动修正特性进行隐式校验,第二种通过手动解析年月日并检查边界值(如闰年、大小月)进行显式校验。代码包含详细注释,适用于前端查询条件的日期合法性检查。
日期有效性校验概述
以下将通过具体的 JavaScript 代码示例,详细介绍如何验证日期有效性。代码结构清晰且包含必要注释,欢迎提出改进建议。
在实际应用中,当查询条件包含日期格式(例如“2012-3-4”)时,需要在执行查询前对输入的日期字符串进行有效性校验,以防止无效数据进入系统。

基于 Date 对象的隐式校验法
var snapshot_createTime_begin=$(selector+" input[name='createTime_begin']").val().trim();
var snapshot_createTime_end=$(selector +" input[name='createTime_end']").val().trim();
try{
//判断开始时间是否为有效的日期
if(snapshot_createTime_begin!=""&&new Date(snapshot_createTime_begin).getDate()!=snapshot_createTime_begin.match(/-\d{0,2}$/g)[0].replace(/-/g,"")){
throw new Error();
}
//判断结束时间是否为有效的日期
if(snapshot_createTime_end!=""&&new Date(snapshot_createTime_end).getDate()!=snapshot_createTime_end.match(/-\d{0,2}$/g)[0].replace(/-/g,"")){
throw new Error();
}
if(Date.parse(snapshot_createTime_begin)>Date.parse(snapshot_createTime_end)){
//alert("开始日期不应当超过结束日期!");
alert("开始日期不应当超过结束日期!");
return ;
}
$.extend(pageObj,{
createTimeBegin:snapshot_createTime_begin,
createTimeEnd:snapshot_createTime_end,
});
initPagination();
}catch(e){
//alert("请输入有效日期!")
alert("请输入有效日期!");
}
接下来介绍一种通过 JavaScript 判断年、月、日组合是否构成有效日期的方法。
手动解析日期的显式校验法
function isdate(intYear,intMonth,intDay){
if(isNaN(intYear)||isNaN(intMonth)||isNaN(intDay)) return false;
if(intMonth>12||intMonth<1) return false;
if ( intDay<1||intDay>31)return false;
if((intMonth==4||intMonth==6||intMonth==9||intMonth==11)&&(intDay>30)) return false;
if(intMonth==2){
if(intDay>29) return false;
if((((intYear%100==0)&&(intYear%400!=0))||(intYear%4!=0))&&(intDay>28))return false;
}
return true;
}
上述代码实现了日期有效性的校验逻辑,旨在为开发者提供实用的参考,希望能为您的项目提供帮助。
作者最新文章
JS处理含Emoji或中文的字符串转数组乱码问题
2026-11-05 16:12:28
JS怎么使用展开运算符合并对象
2026-11-05 14:42:18
ES6+环境下判断JS对象为空的简洁写法
2026-11-05 12:12:23
怎么通过replacer函数自定义JS中JSON的格式化输出
2026-11-05 11:19:44
JS正则表达式基础:字面量与RegExp构造函数的区别及常用元字符
2026-11-05 11:16:58
