JavaScript 校验日期有效性:两种实用方案

作者:拾光

时间:2026-10-29

浏览:175

本文介绍两种在 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; 
}

上述代码实现了日期有效性的校验逻辑,旨在为开发者提供实用的参考,希望能为您的项目提供帮助。

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章