DIV CSS 佈局教程網

JS 表單驗證:判斷所選日期不能早於今天
編輯:關於JavaScript     

在需要選擇日期的表單裡(例如預約、發送排程),我們常需要驗證「使用者選的日期不能小於當前日期」。下面這段程式就示範了這個判斷邏輯。

var controldate;
function checkDate(){
controldate= document.getElementById("sendDate").value;
if(controldate==""){
alert('日期不能為空');
return false;
}else{
var day = new Date(); var Year = 0;
var Month = 0;
var Day = 0;
var CurrentDate = "";
//初始化時間
Year = day.getFullYear();
Month = day.getMonth()+1;
Day = day.getDate();

CurrentDate += Year + "-";

if (Month >= 10 )
{
CurrentDate += Month + "-";
}
else
{
CurrentDate += "0" + Month + "-";
}
if (Day >= 10 )
{
CurrentDate += Day ;
}
else
{
CurrentDate += "0" + Day ;
} //alert(CurrentDate);//當前日期

var startDate = new Date(CurrentDate.replace("-",",")).getTime() ;
var endDate = new Date(controldate.replace("-",",")).getTime() ; if( startDate > endDate )
{
alert('選擇日期不能小於當前日期!');
document.getElementById("sendDate").focus();
return false;
}else{
return true;
}
}
}

程式解析

這個驗證函式的流程如下:先取得輸入框的值,若為空則提示「日期不能為空」。接著用 new Date() 取得今天,並手動拼出「YYYY-MM-DD」格式的日期字串——這裡特別對月和日做了補零處理(小於 10 時前面補 0),確保格式統一。

然後把「今天」與「使用者所選日期」都透過 new Date(...).getTime() 轉成毫秒數(時間戳)來比較。若今天晚於所選日期(startDate > endDate),就提示錯誤並把焦點移回輸入框;否則驗證通過。

這裡有個實作小技巧:先把日期字串的 - 用 replace("-",",") 換成逗號再交給 Date 建構,是為了避開部分瀏覽器對「YYYY-MM-DD」字串解析不一致的問題。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved