form이 많은 프로젝트를 할 때 수많은 state와 유효성검사를 쉽게 하기 위해 만들어진 라이브러리입니다
npm install react-hook-form
const {register,watch,handleSubmitformState:{errors},setError,}=useForm({defalutValues:{email:"@naver.com"}})
<input
{...register('password', {
required: 'password is required',
minLength: { value: 5, message: 'Your password is too short' },
})}
placeholder='password'
/>
watch
watch는 form의 입력값들의 변화를 관찰할 수 있게 해주는 함수
이 함수를 통해 form의 입력값을 추적할 수 있다
handleSubmit
유효성검사를 위한 함수
<form onSubmit={handleSubmit(onValid)}></form>
onValid함수가 호출되었다면, form이 모든 validation을 통과했다는 말
required: true
-> boolean을 이용한 필수값
required: "대답을 작성하지 않았습니다"
-> error 발생시 유저에게 보여줄 에러를 작성
minLength: { value: 5, message: 'Your password is too short' }
pattern:{/^[A-ZA-z0-9._%+-]+@naver.com$/, message:""}
->정규식을 이용해서 들어가야할 값을 지정할 수 있다 ex)이메일
mport { useForm } from 'react-hook-form';
interface IForm {
email: string;
name: string;
password: string;
password1: string;
}
function TodoList() {
const {
register,
handleSubmit,
formState: { errors },
setError,
} = useForm<IForm>({
defaultValues: {
email: '@naver.com',
},
}); //useForm() 훅을 통해 모든 유효성검사,state들을 대체할 수 있다
const onValid = (data: IForm) => {
//onValid함수는 form의 데이터가 유효할때만 호출되는 함수
//패스워드 일치검사하는 방법
if (data.password !== data.password1) {
setError('password',
{ message: 'password are not the same' },//패스워드 불일치 시, error메시지
{shouldFoucus:true}); //불일치 된 곳으로 focus이동
}
};
return (
<div>
<form onSubmit={handleSubmit(onValid)}>
<input
{...register('email', {
required: 'email',
pattern: {
value: /^[A-Za-z0-9._%+-]+@naver.com$/,
message: 'Only naver.com emails allowed',
},
})}
placeholder='email'
/>
<span>{errors?.email?.message as string}</span>
<input
{...register('name', { required: 'name is required' })}
placeholder='Name'
/>
<input
{...register('password', {
required: 'password is required',
minLength: { value: 5, message: 'Your password is too short' },
})}
placeholder='password'
/>
<span>{errors?.password?.message as string}</span>
<input
{...register('password1', {
required: 'password is required',
minLength: { value: 5, message: 'Your password is too short' },
})}
placeholder='password'
/>
<span>{errors?.password1?.message as string}</span>
<button>Add</button>
</form>
</div>
);
}
export default TodoList;t;