- React에서 손쉽게 Form을 작성하고 유효성 검사를 하기 위해서 두 라이브러리를 사용해보았다.
npm i react-hook-form
npm i yup
npm i @hookform/resolvers
import { useForm } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import * as yup from "yup";
function Form() {
// yup으로 유효성 검사
const schema = yup.object({
firstName: yup.string().required("이름을 입력해 주세요."),
lastName: yup.string().required("성을 입력해 주세요."),
age: yup
.number()
.typeError("숫자를 입력하세요.")
.positive("나이를 입력하세요")
.min(0, "0보다 큰 나이를 입력해주세요.")
.max(200, "200보다 작은 나이를 입력해주세요.")
.required("나이를 입력해 주세요."),
});
const {
register,
handleSubmit,
formState: { errors },
} = useForm({ resolver: yupResolver(schema) });
return (
<form onSubmit={handleSubmit((data) => console.log(data))}>
<input {...register("firstName")} placeholder="firstname" />
{errors.firstName && <p>{errors.firstName.message}</p>}
<br />
<input
{...register("lastName", { required: true })}
placeholder="lastname"
/>
{errors.lastName && <p>{errors.lastName.message}</p>}
<br />
<input {...register("age", { pattern: /\d+/ })} placeholder="age" />
{errors.age && <p>{errors.age.message}</p>}
<br />
<input type="submit" />
</form>
);
}
export default Form;
- 위의 코드를 살펴보면, yupResolver를 통해서 react form hook에 yub을 연결할 수 있다.
- yub을 통해 입력받은 데이터의 타입을 검증할 수 있다.
- required를 통해서 값을 꼭 입력받게 할 수 있고, 타입에 따라서 추가적인 검증도 가능하다.
'React' 카테고리의 다른 글
낙관적 업데이트 - Optimistic update (with React) (0) | 2022.11.19 |
---|---|
간단한 React 커스텀 훅(Custom Hook) 사용법 (0) | 2022.11.18 |
ContextAPI 사용하기 (0) | 2022.11.14 |
axios의 interceptors 기능 사용하기 (0) | 2022.11.11 |
useEffect의 Clean-up 함수 (0) | 2022.11.10 |