問題說明
如果使用者一聚焦在欄位並開始輸入,就顯示驗證錯誤,會顯得過早且干擾。舉例來說,當使用者輸入電子郵件地址 (例如「user@gm」) 或有複雜要求的密碼時,該欄位在技術上會視為無效,直到輸入完成為止。標準 :invalid 樣式會導致錯誤狀態立即出現,讓使用者感到挫折。
解決方法
:user-invalid 虛擬類別可讓您延遲錯誤狀態,直到使用者「提交」值 (透過模糊處理欄位) 或嘗試提交表單。這樣一來,只有在使用者完成與欄位的互動後,系統才會提供驗證意見回饋。
導入策略
- HTML 限制:請務必使用
type="email"、pattern和required等標準 HTML5 屬性,觸發瀏覽器的內建驗證邏輯。 - 視覺回饋:請務必使用
:user-invalid,在互動後才套用錯誤樣式。 - 正向強化:建議使用
:user-valid,在符合要求時顯示綠色「成功」指標。 - 順利復原:使用者將輸入內容更正為有效格式後,
:user-invalid就會停止比對,並立即移除錯誤狀態。
導入指南
用途 1:電子郵件驗證
強制規定:電子郵件欄位必須使用標準 HTML5 屬性。錯誤訊息預設為隱藏,只有在瀏覽器判斷使用者離開欄位時處於無效狀態,才會顯示。
<form>
<div class="field">
<label for="email">Email Address</label>
<!-- MANDATORY: Place format hints above the input so autocomplete popovers don't cover them during editing -->
<span id="email-hint" class="hint">Format: you@example.com</span>
<!-- DO: Use standard HTML validation attributes like type="email" and required -->
<input
type="email"
id="email"
name="email"
required
autocomplete="email"
aria-describedby="email-hint"
aria-errormessage="email-error"
>
<div id="email-error" class="error-msg">
<span aria-hidden="true">❌</span> Please enter a valid email address.
</div>
</div>
</form>
.hint {
display: block;
color: #5f6368;
font-size: 0.85rem;
margin-bottom: 0.25rem;
}
.error-msg {
display: none;
color: #d93025;
font-size: 0.875rem;
margin-top: 0.25rem;
}
/*
DO: Only show error styles after user interaction.
Use multiple indicators (border/background shift + icon/text) to avoid color-only states.
*/
input:user-invalid {
border-color: #d93025;
background-color: #fce8e6;
}
/* DO: Reveal the error message using the adjacent sibling selector */
input:user-invalid + .error-msg {
display: block;
}
/* DO: Provide a clear success indication on :user-valid */
input:user-valid {
border-color: #188038;
}
應用實例 2:密碼複雜度
強制:請在 pattern 屬性中使用 Regex Lookahead 模式定義複雜度規則。輸入欄位上方會顯示規則清單,引導使用者輸入正確資訊,如有錯誤則會醒目顯示。
<form>
<div class="field">
<label for="password">New Password</label>
<!-- MANDATORY: Place hints and rules above the input so mobile keyboards do not obscure them -->
<ul id="password-rules" class="rules-list">
<li>At least 8 characters</li>
<li>One uppercase letter</li>
<li>One number</li>
<li>One special character</li>
</ul>
<!-- DO: Use pattern and minlength for complex password validation
DO: Match all constraints with lookaheads via pattern attribute
-->
<input
type="password"
id="password"
autocomplete="new-password"
required
pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[\W_]).{8,}"
minlength="8"
aria-describedby="password-rules"
>
</div>
</form>
/* DO: State the default styling as neutral */
.rules-list {
color: #5f6368;
margin-bottom: 0.5rem;
}
/* DO: Show invalid state (After interaction): Error */
input:user-invalid {
border-color: #d93025;
background-color: #fce8e6;
}
/* DO: Highlight rules list when error is shown using the modern :has() selector */
.field:has(input:user-invalid) .rules-list {
color: #d93025;
font-weight: 600;
}
/* DO: Add success indications for :user-valid state */
input:user-valid {
border-color: #188038;
}
/* DO: Hide rules once satisfied */
.field:has(input:user-valid) .rules-list {
display: none;
}
備用廣告和瀏覽器支援
:user-valid 和 :user-invalid 的備用方案和瀏覽器支援
備用 CSS
input:user-invalid,
input.user-invalid-fallback {
border-color: #d93025;
background-color: #fce8e6;
}
input:user-invalid + .error-msg,
input.user-invalid-fallback + .error-msg {
display: block;
}
JavaScript 備用廣告
使用可重複使用的公用程式,透過 WeakMap 追蹤互動狀態。這可避免 DOM 受到「不乾淨」的類別或資料屬性汙染。
const UserInvalidFallback = (() => {
const dirtyState = new WeakMap();
const updateState = (input) => {
const isValid = input.checkValidity();
// Update both visual and ARIA state
input.classList.toggle('user-invalid-fallback', !isValid);
input.classList.toggle('user-valid-fallback', isValid);
if (!isValid) {
input.setAttribute('aria-invalid', 'true');
} else {
input.removeAttribute('aria-invalid');
}
};
const handleEvent = (event) => {
const input = event.target;
if (event.type === 'reset') {
const controls = input.elements || [];
for (const control of controls) {
dirtyState.delete(control);
control.classList.remove('user-invalid-fallback');
control.classList.remove('user-valid-fallback');
control.removeAttribute('aria-invalid');
}
return;
}
if (!input.checkValidity) return;
if (event.type === 'input' || event.type === 'change') {
const state = dirtyState.get(input) || { hasInteracted: false, hasBlurred: false };
state.hasInteracted = true;
dirtyState.set(input, state);
if (state.hasBlurred) {
updateState(input);
}
} else if (event.type === 'blur') {
const state = dirtyState.get(input) || { hasInteracted: false, hasBlurred: false };
state.hasBlurred = true;
dirtyState.set(input, state);
if (state.hasInteracted) {
updateState(input);
}
}
};
const init = (root = document) => {
if (CSS.supports('selector(:user-invalid)')) return;
root.addEventListener('blur', handleEvent, true); // Capture phase
root.addEventListener('input', handleEvent);
root.addEventListener('change', handleEvent);
root.addEventListener('reset', handleEvent, true); // Capture resets
};
return { init };
})();
// Initialize for a specific form
const form = document.querySelector('#demo-form');
UserInvalidFallback.init(form);
其他考量
- 無障礙中心:
- 必要:使用
aria-describedby將規則清單連結至輸入內容。 - 不建議:在輸入有效前完全隱藏規則清單;使用者需要知道要輸入什麼!
- 必要:使用
- 模式屬性限制:必要:
pattern屬性會執行完整比對 (隱含^...$)。請確保密碼規則運算式涵蓋整個字串。 - 驗證嚴格程度:請注意,瀏覽器的預設
type="email"驗證相當寬鬆 (例如user@localserver可能會通過)。如需更嚴格的驗證,可能需要使用更強大的驗證程式庫,或搭配type="email"使用自訂驗證函式。 - 焦點管理:必要:如果使用者提交的表單含有無效欄位,瀏覽器會自動將焦點移至第一個無效欄位。提交表單也算互動,因此系統會立即套用
:user-invalid樣式。 - 一致的 ARIA 體驗:原生
:user-invalid不會自動與 ARIA 屬性同步。新增下列 JavaScript,讓aria-invalid與視覺狀態保持同步:
// Sync aria-invalid with the CSS :user-invalid state
const syncAria = (el) => {
el.setAttribute?.('aria-invalid', el.matches(':user-invalid') ? 'true' : 'false');
};
// Update on blur (to show error) and input (to clear it)
document.addEventListener('blur', (e) => syncAria(e.target), true);
document.addEventListener('input', (e) => {
if (e.target.hasAttribute('aria-invalid')) syncAria(e.target);
});