萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> Android 開發

HTML5 新型 Input 類型完整指南:email、tel、number、date、url、range 等 13 種輸入控件詳解

HTML5 豐富表單控件概覽

HTML5 引入 13 種新的 ``,提供原生 UI、驗證、鍵盤優化與語意化,大幅減少 JavaScript 驗證與自定義控件開發成本。

13 種新輸入類型詳細表

Type用途原生 UI/鍵盤驗證規則屬性範例
email電子郵件鍵盤含 @ . _符合 RFC 5322 簡化格式multiple (多信箱)
tel電話號碼數字鍵盤 (含 * #)**無內建格式驗證** (全球格式差異大)pattern="[0-9+\-() ]{7,}"
url網址鍵盤含 : / .必含 scheme (https://...)
number數值數字鍵盤 + 微調按鈕數值型別、min/max/stepmin="0" max="100" step="0.1"
range範圍滑桿滑桿 UI數值、min/max/stepmin="0" max="100" step="1"
date日期 (年月日)日期選擇器ISO 8601 (YYYY-MM-DD)min="2024-01-01" max="2024-12-31"
datetime-local本地日期時間 (無時區)日期時間選擇器YYYY-MM-DDTHH:MMstep="60" (分鐘間隔)
month年月年月選擇器YYYY-MM
week年週週選擇器YYYY-Www
time時間 (時分秒)時間選擇器HH:MM[:ss[.mmm]]step="300" (5分鐘間隔)
color顏色選擇器調色盤 UI#RRGGBB (7 字元)
search搜尋框帶清除按鈕、圓角 (WebKit)無特殊驗證placeholder、autosave、results
file檔案選擇檔案選擇對話框accept、multiple、captureaccept="image/*,.pdf"

關鍵屬性與驗證 API

通用屬性

  • required:必填
  • placeholder:提示文字
  • min/max/step:數值/日期/時間範圍與步進
  • pattern:正則表達式驗證 (適用 text, tel, url, email, password 等)
  • autocomplete:自動填充提示 (on/off/email/username/current-password 等)
  • list:關聯 `` 提供建議選項

Constraint Validation API (原生驗證無需 JS)

const input = document.querySelector('input[type="email"][required]');

// 檢查有效性
if (!input.validity.valid) {
    console.log(input.validationMessage); // 瀏覽器內建錯誤訊息 (已本地化)
    input.reportValidity(); // 顯示氣泡提示並聚焦
}

// 自訂錯誤訊息
input.setCustomValidity('請輸入公司信箱 (結尾 @company.com)');
if (!input.value.endsWith('@company.com')) {
    input.setCustomValidity('請輸入公司信箱 (結尾 @company.com)');
} else {
    input.setCustomValidity(''); // 清除自訂錯誤
}

CSS 偽類樣式化驗證狀態

input:valid { border-color: #28a745; }
input:invalid { border-color: #dc3545; }
input:required:invalid { background: #fff0f0; }
input:focus:invalid { box-shadow: 0 0 0 0.2rem rgba(220,53,69,.25); }
input:in-range { background: #f0fff0; }
input:out-of-range { background: #fff0f0; }

瀏覽器相容性與回退策略 (2024 現況)

TypeChromeFirefoxSafariEdge回退行為
email, url, tel, number✅✅✅✅退化為 text
date, datetime-local, month, week, time✅✅ (部分 UI 差異)✅ (iOS 14+ / macOS 11+)✅退化為 text,**需 Polyfill** (如 better-dateinput-polyfill)
color✅✅✅✅退化為 text (需 7 字元 #RRGGBB)
range✅✅✅✅退化為 text (需 JS 滑桿 Polyfill)
search✅✅✅✅退化為 text

實戰最佳實踐

  1. 優先使用原生類型:獲得免費驗證、語意化、無障礙 (ARIA) 支援、行動裝置鍵盤優化。
  2. 搭配 pattern 微調驗證:``。
  3. 提供伺服器端二次驗證:前端驗證可繞過,後端永遠是最後防線。
  4. 優雅降級:使用 Modernizr 或 `@supports` 檢測支援度,為不支援的瀏覽器載入 Polyfill (如日期選擇器、滑桿)。
  5. 無障礙 (a11y):確保 `

完整 Demo 程式碼

<!DOCTYPE html>
<html lang="zh-Hant">
<head>
  <meta charset="UTF-8">
  <title>HTML5 Input Types Demo</title>
  <style>
    form { max-width: 400px; margin: 2rem auto; font-family: system-ui; }
    label { display: block; margin: 1rem 0 0.25rem; font-weight: 500; }
    input { width: 100%; padding: 0.5rem; font-size: 1rem; border: 1px solid #ccc; border-radius: 4px; box-sizing: border-box; }
    input:invalid { border-color: #dc3545; }
    input:valid { border-color: #28a745; }
    button { margin-top: 1rem; padding: 0.75rem 1.5rem; background: #0d6efd; color: white; border: none; border-radius: 4px; cursor: pointer; }
  </style>
</head>
<body>
  <form id="demo-form" novalidate>
    <label>Email: <input type="email" name="email" required placeholder="user@example.com"></label>
    <label>手機: <input type="tel" name="phone" pattern="09\d{8}" required placeholder="0912345678" title="09 開頭 10 碼"></label>
    <label>網址: <input type="url" name="url" placeholder="https://example.com"></label>
    <label>年齡 (18-100): <input type="number" name="age" min="18" max="100" step="1"></label>
    <label>滿意度 (1-10): <input type="range" name="satisfaction" min="1" max="10" value="5"></label>
    <label>生日: <input type="date" name="birthday" max="2006-12-31"></label>
    <label>約會時間: <input type="datetime-local" name="appt"></label>
    <label>主題色: <input type="color" name="theme" value="#0d6efd"></label>
    <label>搜尋: <input type="search" name="q" placeholder="關鍵字" autosave="mysearch" results="5"></label>
    <button type="submit">送出 (開啟主控台查看 validity)</button>
  </form>
  <script>
    document.getElementById('demo-form').addEventListener('submit', e => {
      e.preventDefault();
      const form = e.target;
      if (form.checkValidity()) {
        console.log('✅ 表單驗證通過', Object.fromEntries(new FormData(form)));
      } else {
        console.log('❌ 驗證失敗', form.reportValidity());
      }
    });
  </script>
</body>
</html>

總結

HTML5 新型 Input 類型是現代表單開發的基石。善用它們能獲得**原生驗證、行動裝置鍵盤優化、無障礙支援、語意化 SEO 優勢**,並大幅減少自定義 JavaScript 驗證代碼。關鍵在於理解各類型的**原生 UI 差異、驗證規則、屬性組合**,並制定**優雅降級策略**應對舊瀏覽器。

copyright © 萬盛學電腦網 all rights reserved