Zod란 무엇인가?

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;

Zod를 사용하여 양식 스키마 정의

fomrData구조에 Zod를 사용하여 TypeScript 지원 양식 스키마 만들기

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
  });

사용자 스키마:

검증을 위해 Zod를 React-Hook-Form과 통합하는 방법