formState: error의 종류도 알려주고, 메시지도 따로 작성 가능하다. 모든 속성에 message 작성 가능interface IForm {
email: string;
firstName: string;
lastName: string;
username: string;
password: string;
password1: string;
extraError?: string;
}
function ToDoList() {
const {
register,
handleSubmit,
formState: { errors },
setError,
} = useForm<IForm>({
defaultValues: {
email: "@naver.com",
},
});
const onValid = (data: IForm) => {
if (data.password !== data.password1) {
setError(
"password1",
{ message: "Password are not the same" },
{ shouldFocus: true }
);
}
// setError("extraError", { message: "Server offline." });
};
console.log(errors);
return (
<div>
<form
style={{ display: "flex", flexDirection: "column" }}
onSubmit={handleSubmit(onValid)}
>
<input
{...register("email", {
required: "Email is required",
pattern: {
value: /^[A-Za-z0-9._%+-]+@naver.com$/,
message: "Only naver.com emails allowed",
},
})}
placeholder="Email"
/>
<span>{errors?.email?.message}</span>
<input
{...register("firstName", {
required: "write here",
validate: {
noMinho: (value) =>
value.includes("minho") ? "no minho allowed" : true,
noNick: (value) =>
value.includes("nick") ? "no nick allowed" : true,
},
})}
placeholder="First Name"
/>
<span>{errors?.firstName?.message}</span>
<input
{...register("lastName", { required: "write here" })}
placeholder="Last Name"
/>
<span>{errors?.lastName?.message}</span>
<input
{...register("username", { required: "write here", minLength: 10 })}
placeholder="Username"
/>
<span>{errors?.username?.message}</span>
<input
{...register("password", { required: "write here", minLength: 5 })}
placeholder="Password"
/>
<span>{errors?.password?.message}</span>
<input
{...register("password1", {
required: "Password is required",
minLength: {
value: 5,
message: "Your password is too short.",
},
})}
placeholder="Password1"
/>
<span>{errors?.password1?.message}</span>
<button>Add</button>
<span>{errors?.extraError?.message}</span>
</form>
</div>
);
}
강의 #6.7-6.8을 듣고 정리해보았다.
생각보다 폼 쪽 작업할게 많은데 이 훅은 정말 말도 안되는 거 같다..
리액트로 회원가입 만들기 세상에서 제일 간단할듯!!