JavaScript 日期格式檢查
網頁開發中使用者進行輸入資料。判斷使用者輸入日期格式是否為 YYYY/MM/DD JavaScript 日期格式檢查表單日期格式,用來判斷使用者輸入的日期格式是否符合預期的方法。最好在客戶端 JavaScript 送出資料時驗證日期值是否正確,使用正則表達式 Regular Expression 來定義規則。正則表達式來檢查字串模式的語法,可以用來尋找檢索 match 匹配、search 搜尋或 test, exec 檢測使用者輸入的字串是否符合該規則。
JavaScript
但是這樣只是檢驗其最大限制值,必須再進一步解析大月、小月、閨月的問題,否則會出現不合法的日期。
function dateValidationCheck(str) {
let re = new RegExp("^([0-9]{4})[./]{1}([0-9]{1,2})[./]{1}([0-9]{1,2})$");
let strDataValue;
let infoValidation = true;
if ((strDataValue = re.exec(str)) != null) {
let i;
i = parseFloat(strDataValue[1]);
if (i <= 0 || i > 9999) {
infoValidation = false;
}
i = parseFloat(strDataValue[2]);
if (i <= 0 || i > 12) {
infoValidation = false;
}
i = parseFloat(strDataValue[3]);
if (i <= 0 || i > 31) {
infoValidation = false;
}
} else {
infoValidation = false;
}
if (!infoValidation) {
alert("請檢查輸入 YYYY/MM/DD 日期格式");
}
return infoValidation;
}
Html
<form method="post" name="dateCheckFrom"
onsubmit="return dateValidationCheck(this.date.value);">
<p>請依格式輸入日期 YYYY/MM/DD:</p>
<input type="text" name="date" size="15" />
<input type="submit" value="送出資料" />
</form>
判斷檢驗日期是否正確
使用 Date.parse 但是解讀字串傳回其總毫秒數,使用 Date.parse 由於瀏覽器之間可能的不同與差異問題。
Date.parse("2019-02-29") // Firefox NaN
Date.parse("2019-02-29") // Chrome 1551398400000
Date.parse("2019-02-29") // Edge 1551398400000
Date.parse("2019-02-29") // Opera 1551398400000
嘗試將日期字串使用 new Date() 但需要將結果以 getFullYear(), getMonth() 及 getDate() 提取,再次比照原輸入日期字串,會有些麻煩但是可以得到瀏覽器之間的一致。
new Date("2019/02/29").toLocaleString();
// '2019/3/1 上午12:00:00'
💡 其中 toLocaleString() 回傳依「電腦系統」的地區設定輸出的日期時間字串,只是用中文比較易讀。
let oDate = new Date("2019-02-29")
// Date Fri Mar 01 2019 00:00:00 GMT+0800 (台北標準時間)
如此其輸入日期字串的月份及日、就是 false 不一樣、需要依使用者輸入之欄位方式來拆解判斷。
let cYear = oDate.getFullYear();
let cMonth = oDate.getMonth() + 1;
let cDate = oDate.getDate();
輸入日期字串 iYear, iMonth, iDate
let result = (iYear == cYear) && (iMonth == cMonth) && (iDate == cDate);
年
月
日
功能 : 判斷 v 是否是整數
如果輸入日期以年、月、日、分別輸入或許會需要判斷是否為數值。
function IsInt(n) {
let check = n.match(/^[0-9]+$/);
if (check == null) {
return false;
} else {
return true;
}
}
使用函式 IsNumeric 判斷數值
let IsNumeric = function (input) {
return (input - 0) == input && input.length > 0;
}
IsNumeric("-1") = true
IsNumeric("-1.5") = true
IsNumeric("0") = true
IsNumeric(".38") = true
IsNumeric("1120") = true
IsNumeric("1e+3") = true
IsNumeric("0x89f") = true
IsNumeric("2,600") = false
IsNumeric("Numeric") = false
IsNumeric("") = false