yarn add @hookform/resolvers yup
// or
npm install @hookform/resolvers yup
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();
useForm
에 yupResolver
로 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();
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은 Form validation을 위한 라이브러리이다.
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();
}),
});