useState를 사용해서 각 input의 입력의 validation, error 등 확인 및 값 저장이 필요.
import { useState } from "react";
function ToDoList() {
const [toDo, setToDo] = useState("");
const [toDoError, setToDoError] = useState("");
const onChange = (event: React.FormEvent<HTMLInputElement>) => {
const {
currentTarget: { value },
} = event;
setToDo(value);
setToDoError("");
};
const onSubmit = (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
if (toDo.length < 10) {
return setToDoError("To do should be longer");
}
console.log("submit");
};
return (
<div>
<form onSubmit={onSubmit}>
<input
value={toDo}
onChange={onChange}
type="text"
placeholder="Write a to do"
/>
<button>Add</button>
{toDoError !== "" ? toDoError : null}
</form>
</div>
);
}
export default ToDoList;
form 라이브러리 사용하는 방법
react-hook-form
https://react-hook-form.com/get-started
https://legacy.react-hook-form.com/v6/api/
npm install react-hook-form 설치useForm import하여 사용.// console.log(register("toDo"))
name: "toDo"
onBlur:async event => {…}
onChange: async event => {…}
ref: ref => {…}
input에 {...register("name")}형태로 register가 반환하는 객체들을 펼쳐서 input의 props로 부여.
<input {...register("Email")} placeholder="Email" />
validator.d.ts).
<input
{...register("password", { required: true, minLength: 5 })}
placeholder="password"
/>
// 메세지 추가
<input
{...register("FirstName", {
required: "First name is required",
minLength: {
value: 2,
message: "your first name is way too short",
},
})}
required
placeholder="FirstName"
/>
정규식(regular expressions)를 이용해서 validation 확인도 가능
<input
{...register("Email", {
required: true,
pattern: {
value : /^[A-Za-z0-9._%+-]+@naver.com$/,
message : "Only naver.com emails allowed"
}
})}
placeholder="Email"
/>
validate로 input내에서 별도의 값 확인도 가능.
바로 string을 return하면(validate:"string") errors.message로 동작.
validate 여러 개의 조건일 경우. 오브젝트 형태로 쓸 수 있다.
<input
{...register("firstName", {
required: "First name is required",
minLength: {
value: 2,
message: "your first name is way too short",
},
validate: (value) =>
value.includes("subin") ? "no subin is allowed" : true,
// firstName 값에 subin이 포함되지 않을 경우만 validation true 확인.
})}
placeholder="firstName"
/>
// validate 여러 개
<input
{...register("userName", {
required: "Write here",
validate:
noSubin: (value) =>
value.includes("subin") ? "no subin is allowed" : true,
noNico: (value) =>
value.includes("nico") ? "no nico is allowed" : true,
},
})}
placeholder="userName"
/>
formState : { errors })로 확인 가능password1:{type: 'minLength', message: '', ref: input}
<form onSubmit={handleSubmit(onValid)}>
const onValid = (data: IForm) => {
setError(
"password1",
{ message: "Password are not the same" },
{ shouldFocus: true }
);
}
};
const handleValid = (data: IForm) => {
setValue("password1", "");
};