CSS3 提供表單驗證偽類選擇器,配合 HTML5 表單屬性(required、type="email"、pattern 等),無需撰寫 JavaScript 即可實現即時視覺回饋。支援瀏覽器:Chrome、Firefox、Safari、IE9+。
| 偽類 | 含義 | 觸發時機 |
|---|---|---|
:required | 必填欄位 | 擁有 required 屬性的輸入框 |
:valid | 內容符合驗證規則 | 輸入值通過型別/模式/必填檢查 |
:invalid | 內容不符合驗證規則 | 輸入值未通過檢查(含空值的 required 欄位) |
input:required,
input:valid,
input:invalid {
border: 0 none;
outline: 0 none;
-webkit-box-shadow: none;
-moz-box-shadow: none;
-ms-box-shadow: none;
-o-box-shadow: none;
box-shadow: none;
}
/ 必填欄位標示紅色星號(需配合 label::after)
input:required + label::after {
content: " *";
color: #e74c3c;
}
/ 輸入錯誤時:紅色邊框 + 錯誤圖示背景
input:invalid:not(:placeholder-shown) {
border: 2px solid #e74c3c;
background-image: url("data:image/svg+xml,...");
background-repeat: no-repeat;
background-position: right 0.5rem center;
}
/ 輸入正確時:綠色邊框 + 成功圖示
input:valid:not(:placeholder-shown) {
border: 2px solid #27ae60;
background-image: url("data:image/svg+xml,...");
background-repeat: no-repeat;
background-position: right 0.5rem center;
}
required:必填type="email":電子郵件格式type="url":網址格式type="number" + min/max/step:數值範圍pattern="regex":自訂正則(如手機 ^09\d{8}$)minlength/maxlength:長度限制若需自訂錯誤訊息或程式化控制,可使用 JS API:
const input = document.querySelector('input[required]');
input.addEventListener('invalid', (e) => {
e.preventDefault(); // 取消瀏覽器預設氣泡提示
if (input.validity.valueMissing) {
input.setCustomValidity('請填寫此欄位');
} else if (input.validity.typeMismatch) {
input.setCustomValidity('格式不正確');
}
input.reportValidity(); // 顯示自訂訊息
});
input.addEventListener('input', () => input.setCustomValidity(''));
:invalid 在欄位為空時即匹配(若有 required),建議搭配 :not(:placeholder-shown) 避免一進頁就顯示錯誤。