React Hook Form 유효성 검사

✔️ @hookform/resolvers yup 설치

yarn add @hookform/resolvers yup
// or
npm install @hookform/resolvers yup



Schema Validation


✔️ schema 설정하기

import { useForm } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import * as yup from "yup";

const schema = yup
  .object({
    title: yup
      .string()
      .required("제목을 입력해주세요 😰")
      .min(2, "2자 이상 입력해주세요!"),
    body: yup.string().required("내용을 입력해주세요 😦"),
  })
  .required();


✔️ useFormyupResolverschema 적용하기

import { useForm } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import * as yup from "yup";

const schema = yup
  .object({
    title: yup
      .string()
      .required("제목을 입력해주세요 😰")
      .min(2, "2자 이상 입력해주세요!"),
    body: yup.string().required("내용을 입력해주세요 😦"),
  })
  .required();

export default function App() {
  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm<IFormInputs>({
    resolver: yupResolver(schema),
  });

  const addItem = () => {
    // ...
  };

  return (
    <InputWrap onSubmit={handleSubmit(addItem)}>
      <div className='inputWrap'>
        <div className='input'>
          <input
            type='text'
            placeholder='Todo 제목을 입력해보세요!'
            {...register("title")}
          />
          <p className='message'>{errors.title?.message}</p>
        </div>
        <div className='input'>
          <input
            type='text'
            placeholder='Todo 내용을 입력해보세요!'
            {...register("body")}
          />
          <p className='message'>{errors.body?.message}</p>
        </div>
      </div>
      <input className='button' type='submit' value='등록' />
    </InputWrap>
  );
}



yup ??

YupForm validation을 위한 라이브러리이다.


✔️ yup 기본

import * as yup from "yup";

let schema = yup.object().shape({
  name: yup.string().required(),
  age: yup.number().required().positive().integer(),
  email: yup.string().email(),
  website: yup.string().url(),
  createdOn: yup.date().default(function () {
    return new Date();
  }),
});