以下主要透過 JS 程式碼為大家介紹日期有效性校驗的做法,程式碼相當簡單並附有註解,若有更好的建議也歡迎提出。
如下圖所示,當查詢條件含有日期時(例如「2012-3-4」),在查詢前需先校驗輸入的日期字串是否為有效日期。

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("請輸入有效日期!"); }
以 JS 判斷年月日是否為有效日期:
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; }
以上程式碼便是對日期有效性的校驗,希望對大家有所幫助。