核心屬性速查
| 屬性 | 說明 | 適用類型 |
type | 控件類型(預設 text) | 所有 |
name | 表單提交鍵名 | 所有 |
value | 初始/當前值 | 所有 |
placeholder | 提示文字(非 label 替代) | text, email, url, tel, password, search |
required | 必填驗證 | 所有(除 hidden, button, submit, reset) |
disabled | 禁用,不提交數值 | 所有 |
readonly | 唯讀,仍提交數值 | text, email, url, tel, password, date, number |
autocomplete | 瀏覽器自動填充提示 | text, email, password 等 |
常用 type 類型與驗證
<!-- 文字類 -->
<input type="text" name="username" required minlength="3" maxlength="20" pattern="[A-Za-z0-9_]+">
<input type="email" name="email" required>
<input type="password" name="pwd" required minlength="8">
<input type="search" name="q" placeholder="搜尋...">
<input type="tel" name="phone" pattern="[0-9\-]+">
<input type="url" name="site" placeholder="https://example.com">
<!-- 選擇類 -->
<input type="checkbox" name="agree" value="1" required> 同意條款
<input type="radio" name="gender" value="m"> 男
<input type="radio" name="gender" value="f"> 女
<!-- 日期時間(原生 UI,行動裝置體驗佳) -->
<input type="date" name="birth">
<input type="datetime-local" name="appt">
<input type="month" name="salary_month">
<input type="week" name="report_week">
<input type="time" name="alarm">
<!-- 數值/範圍 -->
<input type="number" name="qty" min="0" max="99" step="1">
<input type="range" name="volume" min="0" max="100" step="1">
<!-- 檔案/隱藏/按鈕 -->
<input type="file" name="avatar" accept="image/*">
<input type="hidden" name="csrf" value="token">
<input type="submit" value="送出">
<input type="reset" value="重置">
<input type="button" value="自訂按鈕">
無障礙最佳實踐
- 永遠搭配
<label>:<label for="email">信箱</label> <input id="email" type="email">
- 錯誤訊息掛載
aria-describedby 指向 <span id="err-email" role="alert">。
- 必要欄位加
aria-required="true"(HTML5 required 已語意化)。
- 群組相關控件用
<fieldset><legend>。
表單提交完整範例
<form action="/api/register" method="post" novalidate>
<div>
<label for="name">姓名</label>
<input id="name" name="name" type="text" required autocomplete="name">
<span id="err-name" class="error" role="alert"></span>
</div>
<button type="submit">註冊</button>
</form>
<script>
document.querySelector('form').addEventListener('submit', async e=>{
e.preventDefault();
const form=e.target, data=new FormData(form);
const res=await fetch(form.action,{method:'POST',body:data});
if(!res.ok){ /* 顯示錯誤 */ }
});
</script>