•
문제: 검증 로직이 UI 이벤트 핸들러에 섞임
•
해결: 검증 로직을 컴포넌트 바깥 순수 함수로 분리
// ❌ Before: 검증이 액션에 섞임
function LoginForm() {
const handleSubmit = (e) => {
e.preventDefault()
const email = e.target.email.value // 액션
const password = e.target.password.value // 액션
// 검증 로직이 이벤트 핸들러 안에
const errors = {}
if (!email.includes('@')) {
errors.email = 'Invalid email'
}
if (password.length < 8) {
errors.password = 'Too short'
}
if (Object.keys(errors).length > 0) {
setErrors(errors) // 액션
return
}
login(email, password) // 액션
}
}
JavaScript
복사
// ✅ After
function LoginForm() {
const handleSubmit = () => {
e.preventDefault()
try {
const { email, password } = parseLoginForm({
email: e.currentTarget.email.value,
password: e.currentTarget.password.value,
});
login(email, password)
} catch (e) {
if (err instanceof ValidationError) {
setErrors(err.errors);
}
}
}
// ...
}
function parseLoginForm(fields) {
const errors = {};
const parsed = {};
const fieldValidators = {
email: getEmail,
password: getPassword,
// username: getUsername, ...
};
for (const [field, validator] of Object.entries(fieldValidators)) {
try {
parsed[field] = validator(fields[field]);
} catch (e) {
if (e instanceof FieldError) {
errors[field] = e.message;
} else {
throw e;
}
}
}
if (Object.keys(errors).length > 0) {
throw new ValidationError(errors);
}
return parsed
}
TypeScript
복사
