什麼是:invalid?
:invalid是CSS偽類選擇器,當表單元素的值不符合其定義的驗證規則(如required、pattern、type等)時,該選擇器將應用樣式。
:invalid的使用方法
1. 基礎用法
<input type="email" required placeholder="請輸入有效的郵箱">
<input type="submit" value="提交">
<style>
/* 無效輸入時顯示紅色邊框 */
input:invalid {
border: 2px solid red;
box-shadow: 0 0 3px red;
}
/* 有效輸入時顯示綠色邊框 */
input:valid {
border: 2px solid green;
box-shadow: 0 0 3px green;
}
</style>
在這個示例中:
- 當用户輸入無效郵箱(如"test")或留空必填字段時,輸入框會顯示紅色邊框
- 當輸入有效郵箱(如"test@example.com")時,輸入框會顯示綠色邊框
2. 實際應用示例
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>表單驗證示例</title>
<style>
form {
max-width: 400px;
margin: 2rem auto;
padding: 1.5rem;
border: 1px solid #ddd;
border-radius: 5px;
}
input {
width: 100%;
padding: 0.5rem;
margin: 0.5rem 0;
border: 1px solid #ccc;
border-radius: 4px;
font-size: 1rem;
}
/* 無效輸入樣式 */
input:invalid {
border-color: #d32f2f;
box-shadow: 0 0 3px #d32f2f;
}
/* 有效輸入樣式 */
input:valid {
border-color: #4caf50;
box-shadow: 0 0 3px #4caf50;
}
input:focus:invalid {
outline: none;
box-shadow: 0 0 5px #d32f2f;
}
</style>
</head>
<body>
<form id="myForm" action="#" method="post">
<h2>註冊表單</h2>
<label for="username">用户名 (3-20字符):</label>
<input type="text" id="username" name="username"
required pattern=".{3,20}"
placeholder="請輸入3-20個字符">
<label for="email">郵箱:</label>
<input type="email" id="email" name="email"
required placeholder="example@example.com">
<label for="password">密碼 (至少6位):</label>
<input type="password" id="password" name="password"
required pattern=".{6,}"
placeholder="至少6位">
<input type="submit" value="註冊">
</form>
<script>
// 可選:添加額外的驗證邏輯
document.getElementById('myForm').addEventListener('submit', function(e) {
const password = document.getElementById('password').value;
if (password.length < 8) {
// 自定義錯誤消息
document.getElementById('password').setCustomValidity("密碼至少需要8位");
} else {
document.getElementById('password').setCustomValidity("");
}
});
</script>
</body>
</html>
注意事項
- 瀏覽器兼容性:現代瀏覽器(Chrome, Firefox, Safari, Edge)都支持
:invalid偽類,但IE9及更早版本不支持。 - 生效時機:
- 這些偽類選擇器只在表單元素獲得焦點後才會生效
- 或者在表單提交時生效
- 不能在元素初始化時立即生效
- 自定義錯誤信息:
- 可以使用
setCustomValidity()方法自定義錯誤消息 - 例如:
inputElement.setCustomValidity("請輸入有效的郵箱");
- 覆蓋瀏覽器默認樣式:
- 一些瀏覽器可能對
:invalid有默認樣式 - 需要通過CSS覆蓋這些默認樣式
- 結合JavaScript:
- 可以使用
checkValidity()方法手動觸發驗證 - 例如:
document.getElementById('email').checkValidity();
為什麼需要使用這種驗證方式?
- 提升用户體驗:實時反饋輸入是否有效,無需等待表單提交
- 減少服務器壓力:在客户端就過濾掉無效數據
- 更安全:防止無效數據被提交到服務器