import React, { useState } from "react";
import { useForm } from "react-hook-form";
/* function ToDoList() {
const [toDo, setToDo] = useState("");
const onChange = (event: React.FormEvent<HTMLInputElement>) => {
const {
currentTarget: { value },
} = event;
setToDo(value);
};
const onSubmit = (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
console.log(toDo);
};
return (
<div>
<form onSubmit={onSubmit}>
<input onChange={onChange} value={toDo} placeholder="Write a to do" />
<button>Add</button>
</form>
</div>
);
} */
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: "FirstName is required.",
validate: {
noNico: (value) => value.includes("nico") ? "no nicos allowed" : true,
noNick: (value) => value.includes("nick") ? "no nicks allowed" : true,
}
})} placeholder="First Name" />
<span>{errors?.firstName?.message}</span>
<input {...register("lastName", {
required: "LastName is required."
})} placeholder="Last Name" />
<span>{errors?.lastName?.message}</span>
<input {...register("username", {
required: "Username is required.",
})} placeholder="Username" />
<span>{errors?.username?.message}</span>
<input {...register("password", {
required: "Password is required",
minLength: {
value: 5,
message: "Your password1 is too short"
}
})} placeholder="Password" />
<span>{errors?.password?.message}</span>
<input {...register("password1", {
required: "Password1 is required",
minLength: {
value: 5,
message: "Your password1 is too short"
}
})} placeholder="Password1" />
<span>{errors?.password1?.message}</span>
<button>Add</button>
<span>{errors?.extraError?.message}</span>
</form>
</div>
);
}
export default ToDoList;
728x90
반응형
'프로그래밍 > 프론트엔드' 카테고리의 다른 글
permission denied 권한오류 해결법 Mac M1 (0) | 2024.02.09 |
---|---|
Tailwind CSS IntelliSense 설치해도 자동완성 안될 때 (0) | 2023.06.26 |
[ReactJs, NextJs] 자주쓰는 패키지 설치 명령어 정리 (0) | 2023.06.06 |
[nodejs] 비밀번호 해시 bcrypt.hash, 테이블 참조 populate (0) | 2023.03.29 |
[CSS] scss의 장점 (0) | 2023.01.25 |