제약 조건 유효성 검사 API 기초
제약 조건 유효성 검사 API로 유효성 상태와 사용자 지정 메시지 읽기
제약 조건 유효성 검사 API 기초은(는) CoddyKit의 무료 HTML Academy 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 HTML Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. HTML Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
제약 조건 유효성 검사 API란 무엇인가요?
제약 조건 유효성 검사 API는 양식 유효성 검사 상태를 읽고 설정하는 JavaScript 인터페이스입니다:
- 필드가 유효한지 확인합니다
- 어떤 특정 제약 조건이 실패했는지 읽습니다
- 사용자 지정 오류 메시지를 설정합니다
- 프로그래밍 방식으로 브라우저 유효성 검사 UI를 실행합니다
validity 속성
모든 양식 컨트롤에는 특정 불리언 플래그가 있는 validity 객체가 있습니다:
const input = document.getElementById('email');
const v = input.validity;
console.log(v.valid); // true if all constraints pass
console.log(v.valueMissing); // true if required but empty
console.log(v.typeMismatch); // true if type doesn't match (e.g. bad email)
console.log(v.patternMismatch); // true if pattern fails
console.log(v.tooShort); // true if shorter than minlength
console.log(v.tooLong); // true if longer than maxlength
console.log(v.rangeUnderflow); // true if less than min
console.log(v.rangeOverflow); // true if more than maxcheckValidity 메서드
checkValidity()는 true 또는 false를 반환하고 invalid 이벤트를 발생시킵니다:
const form = document.getElementById('my-form');
// Check entire form:
if (!form.checkValidity()) {
console.log('Form has errors');
}
// Check individual field:
const email = document.getElementById('email');
if (!email.checkValidity()) {
console.log('Email is invalid');
}
// The 'invalid' event fires on invalid fieldsreportValidity 메서드
reportValidity()는 브라우저의 기본 유효성 검사 UI를 표시합니다:
const input = document.getElementById('username');
// Shows native browser error tooltip if invalid:
const valid = input.reportValidity();
console.log(valid); // true or false
// On a form: validates all fields and shows first error:
document.getElementById('form').reportValidity();validationMessage 속성
validationMessage는 브라우저의 오류 메시지 문자열을 반환합니다:
const email = document.querySelector('input[type=email]');
email.value = 'not-an-email';
console.log(email.validationMessage);
// e.g. "Please include an '@' in the email address..."
console.log(email.validity.typeMismatch); // truesetCustomValidity
setCustomValidity(message)는 사용자 지정 유효성 검사 오류를 설정합니다:
const username = document.getElementById('username');
// Check availability on blur:
username.addEventListener('blur', async () => {
const res = await fetch(`/check-username?name=${username.value}`);
const { taken } = await res.json();
if (taken) {
username.setCustomValidity('This username is already taken.');
} else {
username.setCustomValidity(''); // empty string = clear the error
}
});사용자 지정 유효성 검사 상태 지우기
사용자가 문제를 해결하면 사용자 지정 유효성 검사 상태를 지워야 합니다:
const input = document.getElementById('username');
input.addEventListener('input', () => {
// Clear custom error when user starts typing again:
input.setCustomValidity('');
});
input.addEventListener('blur', async () => {
// Re-validate on blur:
const taken = await checkUsername(input.value);
input.setCustomValidity(taken ? 'Username taken' : '');
});invalid 이벤트
유효성 검사에 실패한 양식 컨트롤에서 invalid 이벤트가 발생합니다:
document.querySelectorAll('input').forEach(input => {
input.addEventListener('invalid', (e) => {
e.preventDefault(); // prevent default browser tooltip
// Show your custom error UI instead:
showError(input, input.validationMessage);
});
});will-validate 속성
요소가 제약 조건 유효성 검사에 참여하면 willValidate가 true입니다:
document.querySelectorAll(':input').forEach(el => {
if (el.willValidate) {
console.log(el.name, 'will be validated');
}
});
// Disabled, hidden, or output elements return willValidate = false사용자 지정 유효성 검사에서 validity 사용하기
완전한 사용자 지정 유효성 검사 예제입니다:
<form id="signup" novalidate>
<input type="email" id="email" name="email" required>
<span id="email-err" role="alert"></span>
<button type="submit">Sign Up</button>
</form>
<script>
const form = document.getElementById('signup');
const email = document.getElementById('email');
const err = document.getElementById('email-err');
form.addEventListener('submit', (e) => {
e.preventDefault();
err.textContent = '';
if (email.validity.valueMissing) {
err.textContent = 'Email is required.';
email.focus();
return;
}
if (email.validity.typeMismatch) {
err.textContent = 'Enter a valid email address.';
email.focus();
return;
}
// Submit...
});
</script>ValidityState 플래그 요약
모든 ValidityState 플래그:
valueMissing— 필수이지만 비어 있음typeMismatch— 형식이 잘못됨patternMismatch— 패턴 정규식이 일치하지 않음tooShort/tooLong— minlength/maxlengthrangeUnderflow/rangeOverflow— min/maxstepMismatch— 유효한 단계 값이 아님customError— setCustomValidity 메시지가 설정됨badInput— 브라우저가 값을 해석할 수 없음
빠른 확인
브라우저의 기본 유효성 검사 오류 팝업을 프로그래밍 방식으로 표시하려면 어떻게 해야 하나요?
복습: 제약 조건 유효성 검사 API
제약 조건 유효성 검사 API의 핵심:
input.validity— 특정 플래그가 있는 ValidityState 객체checkValidity()— true 또는 false를 반환하고 invalid 이벤트를 발생시킴reportValidity()— 검사하고 기본 오류 UI를 표시함validationMessage— 브라우저의 오류 문자열setCustomValidity(msg)— 사용자 지정 오류를 설정하며, 빈 문자열을 사용하면 지워짐
자주 묻는 질문
“제약 조건 유효성 검사 API 기초” 강의는 무료인가요?
네 — “제약 조건 유효성 검사 API 기초” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 HTML Academy 강의 전체를 잠금 해제할 수 있습니다. HTML Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
“제약 조건 유효성 검사 API 기초”에서 뭘 배우나요?
제약 조건 유효성 검사 API로 유효성 상태와 사용자 지정 메시지 읽기 브라우저에서 직접 실행하는 실습 코드로 HTML Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
HTML Academy을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 HTML Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.
“제약 조건 유효성 검사 API 기초” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 HTML Academy 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 HTML Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.