<input> 核心屬性
| 屬性 | 說明 |
type | 控件類型(決定 UI 與驗證邏輯) |
name | 表單提交鍵名(必填,否則不提交) |
value | 初始/當前值 |
placeholder | 佔位提示(非替代 label) |
required | 必填驗證 |
disabled | 禁用(不提交、不可聚焦、灰顯) |
readonly | 只讀(可提交、可聚焦、可複製) |
autocomplete | 自動完成提示(on/off/email/username/new-password…) |
autofocus | 頁面加載自動聚焦(每頁僅一個) |
form | 關聯表單 ID(可置於 form 外) |
list | 關聯 <datalist> ID |
pattern | 正則驗證(需配合 title 提示) |
min/max/step | 數字/日期範圍與步長 |
accept | 文件類型過濾(image/*, .pdf, .docx) |
capture | 媒體捕獲來源(user/environment) |
type 類型大全(HTML5 新增標 ★)
| type | 用途 | UI/驗證特性 |
| text | 單行文本 | 無特殊驗證 |
| password | 密碼 | 彈幕顯示、防自動填充 |
| email ★ | 郵箱 | 內建格式驗證、移動鍵盤優化 |
| url ★ | 網址 | 內建格式驗證 |
| tel ★ | 電話 | 移動端彈出撥號盤 |
| number ★ | 數字 | 上下箭頭、min/max/step 驗證 |
| range ★ | 滑塊 | 視覺滑桿、配合 output 顯示值 |
| date ★ | 日期 | 日期選擇器、ISO 8601 格式 |
| datetime-local ★ | 本地日期時間 | 無時區 |
| month/week ★ | 月/周 | 特定選擇器 |
| time ★ | 時間 | 時間選擇器 |
| color ★ | 顏色 | 拾色器、返回 #RRGGBB |
| checkbox | 多選 | 布爾值、可配合 indeterminate |
| radio | 單選 | 同 name 分組互斥 |
| file | 上傳 | accept、multiple、capture |
| submit | 提交按鈕 | 觸發 form submit |
| button | 普通按鈕 | 無默認行為、配合 JS |
| reset | 重置按鈕 | 恢復表單初始值 |
| image | 圖片提交 | src、alt、提交座標 x/y |
| hidden | 隱藏字段 | 不顯示、提交數據 |
無障礙關鍵:<label> 綁定
<!-- 方式一:for + id(推薦,點擊 label 聚焦 input) -->
<label for="username">用戶名</label>
<input type="text" id="username" name="username" required>
<!-- 方式二:包裹(無需 id) -->
<label>郵箱 <input type="email" name="email"></label>
表單驗證最佳實踐
- 優先使用原生屬性(
required, pattern, min/max, type)實現無 JS 驗證。
- 自定義提示:
input.setCustomValidity('錯誤信息') + reportValidity()。
- 樣式鉤子:
:valid, :invalid, :required, :optional, :user-invalid (Firefox)。
- 提交前統一檢查:
form.checkValidity() / form.reportValidity()。
經典示例:登錄表單
<form action="/login" method="post" novalidate>
<div>
<label for="email">郵箱</label>
<input type="email" id="email" name="email" required autocomplete="email" placeholder="you@example.com">
</div>
<div>
<label for="pwd">密碼</label>
<input type="password" id="pwd" name="password" required autocomplete="current-password" minlength="8">
</div>
<button type="submit">登錄</button>
</form>