기타/Bootstrap
[Bootstrap] Form Validation
glorypang
2025. 3. 28. 12:58
728x90
반응형
SMALL
1. 기본 개념
- `form`에 유효성 검사 피드백을 제공하기 위해 다음 두 클래스 중 하나를 사용
- `.was-validated`: 제출 이후 유효성 검사 적용
- `.needs-validation`: 제출 전 사용자 정의 스크립트로 제어하는 방식
2. 필수 속성
- 각 `input`, `select`, `textarea` 요소에 `required` 속성을 넣어야 유효성 검사 동작
- `.valid-feedback` / `.invalid-feedback` 클래스를 활용해 성공/실패 메시지 제공 가능
<form class="was-validated" action="/action_page.php">
<div class="mb-3">
<label for="uname" class="form-label">Username:</label>
<input type="text" class="form-control" id="uname" placeholder="Enter username" name="uname" required>
<div class="valid-feedback">Looks good!</div>
<div class="invalid-feedback">Please fill out this field.</div>
</div>
<div class="mb-3">
<label for="pwd" class="form-label">Password:</label>
<input type="password" class="form-control" id="pwd" placeholder="Enter password" name="pwd" required>
<div class="valid-feedback">Valid password.</div>
<div class="invalid-feedback">Please enter your password.</div>
</div>
<div class="form-check mb-3">
<input class="form-check-input" type="checkbox" id="agree" required>
<label class="form-check-label" for="agree">I agree to the terms</label>
<div class="invalid-feedback">You must agree before submitting.</div>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>

3. 자바스크립트 유효성 검사 + `.needs-validation`
// JavaScript 유효성 검사를 위한 예제
(() => {
'use strict'
const forms = document.querySelectorAll('.needs-validation')
Array.from(forms).forEach(form => {
form.addEventListener('submit', event => {
if (!form.checkValidity()) {
event.preventDefault()
event.stopPropagation()
}
form.classList.add('was-validated')
}, false)
})
})()
728x90
반응형
LIST