React Hook Form

heyj·2022년 2월 17일
0

React 공부하기

목록 보기
4/4
post-thumbnail

React Hook Form 사용하기

1. Apply Validation

공식사이트 : https://react-hook-form.com/get-started

  • 공식사이트를 보면 유효성 체크 규칙을 7가지(required, min, max, minLength, maxLength, pattern, validata) 제공한다고 명시한다.

  • 아래 예제는 4개의 input 중 3개에 대해 유효성 체크 적용, ’firstName’ field는 값이 없으면 안되고 길이는 20까지만 허용하도록 한다. ‘age’ field는 18세~99세까지만 등록할 수 있도록 허용하고 있다.

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

export default function App() {
  const { register, handleSubmit } = useForm();
  const onSubmit = data => console.log(data);
   
  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input {...register("firstName", { required: true, maxLength: 20 })} />
      <input {...register("lastName", { pattern: /^[A-Za-z]+$/i })} />
      <input type="number" {...register("age", { min: 18, max: 99 })} />
      <input type="submit" />
    </form>
  );
}

2. 내 프로젝트에 적용하기

1) register

input이나 select 요소를 등록하거나 유효성 체크 규칙을 적용할 수 있도록 한다.

2) handleSubmit

form의 유효성 체크가 성공적으로 완료되면 form data를 받아 submit하는 함수다.

3) watch

특정 input을 감시하고 input값을 리턴하는 함수. 프로젝트 안에서는 password와 password confirm이 같은 값인지 확인하기 위해 사용한다.

4) formState error

field값이 비어있거나 유효성 체크에 걸린다면 errormessage를 보여주도록 설정할 수 있다.

const { register, handleSubmit, watch, formState: { errors } } = useForm();
const password = useRef();
password.current = watch("password");

const onSubmit = data => {
    console.log("data", data);

    let body = {
      name: data.name,
      email: data.email,
      password: data.password
    };
    user.register(body);
    navigate("/login");
};

<form
  ref={formRef}
  onSubmit={handleSubmit(onSubmit)}
  className={styles.registerform}
>
    <label>Email</label>
    <input
      type="email"
      placeholder="email"
      {...register("email", { required: true, pattern: /^\S+@\S+$/i })}
    />
    {errors.email && <p>This email field is required</p>}

    <label>Name</label>
    <input
      type="text"
      placeholder="name"
      {...register("name", { required: true, maxLength: 10 })}
    />
    {errors.name &&
      errors.name.type === "required" &&
      <p> This name field is required</p>}
    {errors.name &&
      errors.name.type === "maxLength" &&
      <p> Your input exceed maximum length</p>}

    <label>Password</label>
    <input
      type="password"
      placeholder="password"
      {...register("password", { required: true, minLength: 5 })}
    />
    {errors.password &&
      errors.password.type === "required" &&
      <p> This name field is required</p>}
    {errors.password &&
      errors.password.type === "minLength" &&
      <p> Password must have at least 5 characters</p>}

    <label>Password Confirm</label>
    <input
      type="password"
      placeholder="password confirm"
      {...register("password_confirm", {
        required: true,
        validate: value => value === password.current
      })}
    />
    {errors.password_confirm &&
      errors.password_confirm.type === "required" &&
      <p> This password confirm field is required</p>}
    {errors.password_confirm &&
      errors.password_confirm.type === "validate" &&
      <p>The passwords do not match</p>}

  <input type="submit" />
</form>

0개의 댓글