Last active
September 5, 2021 04:52
-
-
Save HeavenOSK/b33325e144aec26b38f9a33dcec41f12 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import type {NextPage} from 'next' | |
import {useForm} from "react-hook-form"; | |
import * as yup from 'yup' | |
import {yupResolver} from "@hookform/resolvers/yup"; | |
import {UseFormRegister} from "react-hook-form/dist/types/form"; | |
import {FieldErrors} from "react-hook-form/dist/types/errors"; | |
type InputId = 'nickname' | 'email' | 'password' | |
type CustomRecord = Record<InputId, any> | |
type FormValues = { | |
nickname: string | |
email: string | |
password: string | |
} | |
const schema = yup.object().shape<CustomRecord>({ | |
nickname: yup.string() | |
.min(2, 'ニックネームは2文字以上20文字以下で入力してください') | |
.max(20, 'ニックネームは2文字以上20文字以下で入力してください') | |
.required('ニックネームは必須項目です'), | |
email: yup.string() | |
.email('メールアドレスを正しい形式で入力してください') | |
.required('メールアドレスは必須項目です'), | |
password: yup.string() | |
.min(8, 'パスワードは8文字以上16文字以下で入力してください') | |
.max(16, 'パスワードは8文字以上16文字以下で入力してください') | |
.required('パスワードは必須項目です'), | |
}) | |
type InputProps = { | |
id: InputId, | |
label: string, | |
register: UseFormRegister<FormValues>, | |
errors: FieldErrors, | |
} | |
const Home: NextPage = () => { | |
const {register, handleSubmit, formState: {errors}} = useForm<FormValues>({ | |
resolver: yupResolver(schema) | |
}) | |
const makeInput = ({id, label, register, errors}: InputProps) => { | |
return <> | |
<label htmlFor={id}> | |
<p>{label}</p> | |
</label> | |
<input | |
id={id} | |
{...register(id)} | |
type={id == 'password' ? 'password' : 'text'} | |
/> | |
{errors[id]?.message && <p>{errors[id]?.message}</p>} | |
</> | |
} | |
return ( | |
<main> | |
<div className="p-4"> | |
<h1 className="text-2xl">新規登録</h1> | |
<form onSubmit={ | |
handleSubmit( | |
(data) => { | |
console.log(`submitted: ${data.nickname}`) | |
console.log(`submitted: ${data.email}`) | |
console.log(`submitted: ${data.password}`) | |
} | |
)}> | |
{ | |
makeInput({ | |
id: 'nickname', | |
label: 'ニックネーム', | |
register: register, | |
errors: errors, | |
}) | |
} | |
{ | |
makeInput({ | |
id: 'email', | |
label: 'メールアドレス', | |
register: register, | |
errors: errors, | |
}) | |
} | |
{ | |
makeInput({ | |
id: 'password', | |
label: 'パスワード', | |
register: register, | |
errors: errors, | |
}) | |
} | |
<input className="block" type="submit"/> | |
</form> | |
</div> | |
</main> | |
) | |
} | |
export default Home |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
使用している package
react-hook-form
@hookform/resolvers
yup