Zod 및 React-Hook-Form을 사용하여 양식을 검증하는 방법
React-Hook-Form은 제어되지 않는 구성 요소를 수용하고 직관적인 후크 기반 API로 양식 작성을 단순화하는 React기반의 폼 관리 라이브러리입니다.
또한, Zod는 데이터 스키마 정의를 위한 간결하고 표현력이 풍부한 구문을 제공하는 유효성 검사 라이브러리로, 양식 데이터 유효성을 검사하는 데 탁월한 선택입니다.
import { useForm } from "react-hook-form";
import FormField from "./FormField";
import { zodResolver } from "@hookform/resolvers/zod";
function Form() {
const {
register,
handleSubmit,
formState: { errors },
setError,
} = useForm<FormData>();
const onSubmit = async (data: FormData) => {
console.log("SUCCESS", data);
}
return (
<form onSubmit={handleSubmit(onSubmit)}>
<div className="grid col-auto">
<h1 className="text-3xl font-bold mb-4">
Zod & React-Hook-Form
</h1>
<FormField
type="email"
placeholder="Email"
name="email"
register={register}
error={errors.email}
/>
<FormField
type="text"
placeholder="GitHub URL"
name="githubUrl"
register={register}
error={errors.githubUrl}
/>
<FormField
type="number"
placeholder="Years of Experience (1 - 10)"
name="yearsOfExperience"
register={register}
error={errors.yearsOfExperience}
valueAsNumber
/>
<FormField
type="password"
placeholder="Password"
name="password"
register={register}
error={errors.password}
/>
<FormField
type="password"
placeholder="Confirm Password"
name="confirmPassword"
register={register}
error={errors.confirmPassword}
/>
<button type="submit" className="submit-button">
Submit
</button>
</div>
</form>
);
}
export default Form;
fomrData구조에 Zod를 사용하여 TypeScript 지원 양식 스키마 만들기
z
Zod 객체의 인스턴스입니다.ZodType
특정 데이터 구조에 대한 Zod 스키마 유형을 나타내는 일반 유형입니다.type.ts
import { z, ZodType } from "zod";
type FormData = {
email: string;
githubUrl: string;
yearsOfExperience: number;
password: string;
confirmPassword: string;
}
export const UserSchema: ZodType<FormData> = z
.object({
email: z.string().email(),
githubUrl: z
.string()
.url()
.includes("github.com", { message: "Invalid GitHub URL" }),
yearsOfExperience: z
.number({
required_error: "required field",
invalid_type_error: "Years of Experience is required",
})
.min(1)
.max(10),
password: z
.string()
.min(8, { message: "Password is too short" })
.max(20, { message: "Password is too long" }),
confirmPassword: z.string(),
})
.refine((data) => data.password === data.confirmPassword, {
message: "Passwords do not match",
path: ["confirmPassword"], // path of error
});
export const UserSchema: ZodType<FormData> =...
UserSchema
는 FormData 유형에 의해 정의된 구조에 해당하는 Zod 유형을 나타냅니다z.object({...})
객체 내에서 각 필드는 z.string()z.url()z.number()z.min()
와 같은 Zod 메서드를 사용하여 자체 유효성 검사 규칙으로 정의됩니다. 일부 필드에는 선택적 사용자 정의 오류 메시지가 제공됩니다.
z.refine((data) => data.password === data.confirmPassword, { /* ... */ });
비밀번호와 ver
passwordconfirmPasswordconfirmPassword
스키마에 refinement를 추가하여 password
및 confirmPassword
필드가 일치하는지 확인합니다. 일치하지 않는 경우, 사용자 정의 오류 메시지가 제공되며, 오류는 confirmPassword
필드와 연관됩니다.