import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
// 1. Zod를 사용하여 폼의 스키마(규칙) 정의
const loginSchema = z.object({
email: z.string().email("올바른 이메일 형식을 입력해주세요."),
password: z.string().min(6, "비밀번호는 최소 6자 이상이어야 합니다."),
});
type LoginFormInputs = z.infer<typeof loginSchema>;
export default function LoginForm() {
// 2. useForm에 zodResolver를 연결하여 검증 위임
const { register, handleSubmit, formState: { errors } } = useForm({
resolver: zodResolver(loginSchema),
});
const onSubmit = (data) => {
console.log("검증 성공! 전송된 데이터:", data);
alert(JSON.stringify(data, null, 2));
};
return (
<div style={{ padding: '20px', background: '#f8fafc', borderRadius: '8px' }}>
<form onSubmit={handleSubmit(onSubmit)} style={{ display: 'flex', flexDirection: 'column', gap: '15px' }}>
<div>
<input
{...register("email")}
placeholder="이메일"
style={{ width: '100%', padding: '10px', borderRadius: '4px', border: '1px solid #cbd5e1' }}
/>
{/* 에러 메시지 출력 */}
{errors.email && <p style={{ color: '#ef4444', fontSize: '0.875rem', marginTop: '5px' }}>{errors.email.message}</p>}
</div>
<div>
<input
type="password"
{...register("password")}
placeholder="비밀번호"
style={{ width: '100%', padding: '10px', borderRadius: '4px', border: '1px solid #cbd5e1' }}
/>
{errors.password && <p style={{ color: '#ef4444', fontSize: '0.875rem', marginTop: '5px' }}>{errors.password.message}</p>}
</div>
<button
type="submit"
style={{ padding: '10px', background: '#3b82f6', color: '#fff', border: 'none', borderRadius: '4px', cursor: 'pointer', fontWeight: 'bold' }}
>
로그인
</button>
</form>
</div>
);
}