萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 日期格式 YYYY-MM-DD 嚴格驗證 (正則 + 邏輯校驗)

表單提交前驗證日期格式與邏輯合法性 (如 2023-02-30 非法) 是基礎防禦性編程。本文提供一個嚴格驗證函數,結合正則格式校驗與 Date 對象自動溢出特性實現真實日期判斷。

核心驗證函數

/**
 * 嚴格驗證 YYYY-MM-DD 格式日期
 * @param {HTMLInputElement|string} obj - input 元素或日期字符串
 * @returns {boolean} 驗證通過返回 true
 */
function checkInputDate(obj) {
    var strDate = (typeof obj === 'string') ? obj : obj.value;
    // 1. 格式正則:四位年-兩位月-兩位日
    var re = /^(\d{4})-(\d{2})-(\d{2})$/;
    var match = strDate.match(re);
    
    if (!match) {
        showError("格式必須為 YYYY-MM-DD");
        return false;
    }
    
    var year = parseInt(match[1], 10);
    var month = parseInt(match[2], 10);
    var day = parseInt(match[3], 10);
    
    // 2. 邏輯校驗:利用 Date 自動溢出特性
    // new Date(2023, 1, 30) -> 2023-03-02 (月份 0-11)
    var dateObj = new Date(year, month - 1, day);
    
    if (dateObj.getFullYear() !== year || 
        dateObj.getMonth() !== month - 1 || 
        dateObj.getDate() !== day) {
        showError("日期不存在 (如 2月30日、4月31日)");
        return false;
    }
    
    // 可選:業務範圍限制 (如不早於 1900 年、不晚於今天)
    // if (year < 1900 || dateObj > new Date()) { showError("日期超出允許範圍"); return false; }
    
    clearError();
    return true;
}

function showError(msg) {
    document.getElementById("errorMessage").innerText = msg;
    document.getElementById("error").style.display = "";
}
function clearError() {
    document.getElementById("error").style.display = "none";
}

HTML 表單示例

<form onsubmit="return checkInputDate(document.getElementById('dateInput'))">
    <input type="text" id="dateInput" placeholder="YYYY-MM-DD" />
    <span id="error" style="display:none; color:red;">
        <span id="errorMessage"></span>
    </span>
    <button type="submit">提交</button>
</form>

原理解析:Date 自動溢出修正

new Date(2023, 1, 28)  // 2023-02-28 (正常)
new Date(2023, 1, 29)  // 2023-03-01 (2023非閏年,2月無29日,自動進位)
new Date(2023, 3, 31)  // 2023-05-01 (4月只有30日)
new Date(2023, 11, 32) // 2024-01-01 (跨年)

利用這一特性:構造 Date(year, month-1, day) 後,若獲取的年月日與輸入不一致,說明原輸入日期非法。

現代替代方案

  • HTML5 原生驗證:<input type="date" required> 瀏覽器自動攔截非法格式與邏輯 (支援度極高,移動端體驗佳)。
  • date-fns / dayjs:
    import { parse, isValid } from 'date-fns';
    const valid = isValid(parse(str, 'yyyy-MM-dd', new Date()));
  • Intl.DateTimeFormat:解析本地化格式,但不直接提供嚴格驗證 API。

正則擴展:支援更多格式

// 支援 YYYY-M-D、YYYY/MM/DD、YYYY.MM.DD 等
var flexibleRe = /^(\d{4})[-.\/](\d{1,2})[-.\/](\d{1,2})$/;
// 匹配後同樣用 Date 校驗邏輯合法性

嚴格的前端日期驗證能攔截 90%+ 格式錯誤,配合後端二次校驗構建雙重防線,保障數據質量。

copyright © 萬盛學電腦網 all rights reserved