문제
페이지 로드 시 필수 입력란을 오류 상태로 표시하면 혼란을 야기할 수 있습니다. 이상적으로는 사용자가 필수 입력란을 작성하려고 시도했으나 실패한 경우에만 '잘못됨'으로 표시되어야 합니다.
해결 방법
:user-invalid 가상 클래스는 이 문제를 완벽하게 해결합니다. 필수 입력란의 경우 페이지 로드 시 일치하지 않습니다. 다음과 같은 경우에만 일치합니다.
- 사용자가 필드와 상호작용 (예: 문자 입력 후 삭제)한 후 필드를 떠나 (blur) 비어 있는 상태로 둡니다.
- 필드가 비어 있는 상태에서 사용자가 양식을 제출하려고 합니다.
구현 전략
- HTML 제약 조건: 입력에
required속성을 추가합니다. - 시각적 피드백:
:user-invalid를 사용하여 테두리를 빨간색으로 스타일 지정하고 '필수' 도우미 텍스트를 표시합니다. - 타이밍: 시각적 피드백을 위해 브라우저의 기본 타이밍을 사용합니다.
touched클래스를 추가하기 위해 더 이상onBlur핸들러가 필요하지 않지만 ARIA 속성을 동기화하려면 여전히 일부 JavaScript가 필요합니다 (아래 참고).
구현 가이드
1. HTML 구조
<form id="feedback-form">
<div class="field">
<label for="full-name">Full Name</label>
<input
type="text"
id="full-name"
name="full-name"
required
aria-errormessage="name-error"
>
<!-- MANDATORY: Include an icon or distinct non-color indicator alongside error text -->
<div id="name-error" class="error-msg">
<span aria-hidden="true">❌</span> This field is required.
</div>
</div>
</form>
2. CSS
.error-msg {
display: none;
color: #d93025;
font-size: 0.875rem;
margin-top: 0.25rem;
}
/*
Only highlight empty required fields AFTER the user visits them.
MANDATORY: Provide multiple indicators (border shift + helper text/icon) to avoid color-only state communication.
*/
input:user-invalid {
border-color: #d93025;
background-color: #fce8e6;
}
input:user-invalid + .error-msg {
display: block;
}
/* Optional: Subtle indicator for required fields that are valid */
input:required:user-valid {
border-color: #188038;
border-width: 2px;
}
3. JavaScript 상태 동기화
필수: :user-invalid는 시각적 상태이므로 사용자가 잘못된 필드를 흐리게 처리하거나 제출을 시도할 때 보조 기술을 위해 aria-invalid="true"를 동적으로 동기화하는 JavaScript 브리지를 제공해야 합니다(MUST).
const form = document.getElementById('feedback-form');
const syncAriaInvalid = (input) => {
if (!input.checkValidity()) {
input.setAttribute('aria-invalid', 'true');
} else {
input.removeAttribute('aria-invalid');
}
};
// Sync on blur when a user finishes interacting
form.addEventListener('blur', (e) => {
if (e.target.matches('input[required]')) {
syncAriaInvalid(e.target);
}
}, true);
// Sync all required fields when submission is attempted
form.addEventListener('submit', () => {
form.querySelectorAll('input[required]').forEach(syncAriaInvalid);
});
// Remove error state immediately upon correction
form.addEventListener('input', (e) => {
if (e.target.matches('input[required]') && e.target.checkValidity()) {
e.target.removeAttribute('aria-invalid');
}
});
대체 및 브라우저 지원
: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);
기타 고려사항
- 별표: 사용자가 상호작용하기 전에 무엇을 입력해야 하는지 알 수 있도록 라벨에 필수 입력란을 시각적으로 표시 (예: 별표
*)하는 것이 좋습니다. - 제출 버튼:
disabled버튼과 달리 제출 버튼은 사용 설정된 상태로 유지합니다. 사용자가 이 버튼을 클릭하면 브라우저가 비어 있는 모든 필수 입력란에서 자동으로:user-invalid를 트리거하고 첫 번째 입력란에 포커스를 맞춥니다. 이는 접근성과 UX에 매우 좋습니다. - 접근성: 네이티브
: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);
});