so woon!

[REACT] React Hook Form - setError 사용하기 본문

ReactJS/개념정리

[REACT] React Hook Form - setError 사용하기

xowoony 2023. 4. 17. 18:42

학습일 : 2023. 04. 17


setError를 react-hook-form으로 부터 꺼내어 드디어 사용해보자

setError는 특정한 에러를 발생시키게 해준다.


 

먼저, formState에 setError를 적어주고

const {
    register,
    handleSubmit,
    formState: { errors },
    setError,
  } = useForm<IForm>({
    defaultValues: {
      email: "@naver.com",
    },
  });

 

 

onVaild 함수에서 if문으로 두개의 비밀번호가 서로 일치하지 않을 경우

setError함수를 불러와주겠다고 해주고

password_check 부분의 

message로 "패스워드가 다릅니다." 가 출력되도록 조치한다.

 const onValid = (data: IForm) => {
    if (data.password !== data.password_check) {
      // setError 적고 hover 해보면 뭐 적어야 할지 타입스크립트 덕분에 알 수 있음
      setError("password_check", {message:"패스워드가 다릅니다."})
    }
  };

 

 

 

전체코드

 

<ToDoList.tsx>

import { useForm } from "react-hook-form";

interface IForm {
  email: string;
  firstname: string;
  lastname: string;
  username: string;
  password: string;
  password_check: string;
}

function ToDoList() {
  const {
    register,
    handleSubmit,
    formState: { errors },
    setError,
  } = useForm<IForm>({
    defaultValues: {
      email: "@naver.com",
    },
  });

  const onValid = (data: IForm) => {
    if (data.password !== data.password_check) {
      setError("password_check", {message:"패스워드가 다릅니다."})
    }
  };

  console.log(errors);
  return (
    <div>
      <form
        style={{
          display: "flex",
          flexDirection: "column",
        }}
        onSubmit={handleSubmit(onValid)}
      >
        <input
          {...register("email", {
            required: "이메일은 필수로 작성해주셔야 합니다.",
            pattern: {
              value: /^[A-Za-z0-9._%+-]+@naver\.com$/,
              message: "오직 naver.com 주소만 허용됩니다.",
            },
          })}
          placeholder="email을 입력해주세요."
        />
        <span>{errors?.email?.message as string}</span>
        <input
          {...register("firstname", { required: "firstname을 입력해주세요." })}
          placeholder="firstname을 입력해주세요."
        />
        <span>{errors?.firstname?.message as string}</span>
        <input
          {...register("lastname", { required: "lastname을 입력해주세요." })}
          placeholder="lastname을 입력해주세요."
        />
        <span>{errors?.lastname?.message as string}</span>
        <input
          {...register("username", {
            required: "username을 입력해주세요.",
            minLength: 3,
          })}
          placeholder="username을 입력해주세요."
        />
        <span>{errors?.username?.message as string}</span>
        <input
          {...register("password", {
            required: "password를 입력해주세요",
            minLength: { value: 5, message: "5자 이상으로 설정해주세요" },
          })}
          placeholder="password를 입력해주세요."
        />
        <span>{errors?.password?.message as string}</span>
        <input
          {...register("password_check", {
            required: "password를 한번 더 입력해주세요",
            minLength: { value: 5, message: "5자 이상으로 설정해주세요" },
          })}
          placeholder="password를 입력해주세요."
        />
        <span>{errors?.password_check?.message as string}</span>
        <button>추가</button>
      </form>
    </div>
  );
}

export default ToDoList;

 

 

 

실행결과

비밀번호 체크 부분이 앞에 입력해준 비밀번호와 일치하지 않을 경우

password_check 부분에 에러가 잘 발생함을 볼 수 있다.

 

 

 

 

Comments