Yupとは
フォームの入力値を解析してバリデーションを行うReactライブラリのこと。
インストール方法
npm install yup
基本的な使い方
// import文
import * as yup from 'yup';
// 文字列型チェック + 必須チェック
yup.string().required('必須エラーメッセージ')
// 数値型チェック + 必須チェック
yup.number().required('必須エラーメッセージ')
// 配列型チェック + 必須チェック
yup.array().min(1, '必須エラーメッセージ')
// 日付型チェック + 必須チェック
yup.date().required('必須エラーメッセージ')
// バリデーションルール設定
const schema = yup.object().shape({
username: yup.string().required(t("auth.message.required_usercd")),
age: yup.number().required(t("auth.message.required_age"))
})
使用例
※ react-hook-formと組み合わせて使用した場合
"use client";
import yup from "yup";
import { yupResolver } from "@hookform/resolvers/yup";
import { useForm, SubmitHandler } from "react-hook-form";
const schema = yup.object().shape({
username: yup.string().required(t("auth.message.required_usercd")),
age: yup.number().required(t("auth.message.required_age"))
})
type exampleFormData = yup.InferType<typeof schema>;
export const ExampleForm = () => {
const { register, handleSubmit, formState } = useForm<exampleFormData>({
resolver: yupResolver(schema), // Yupと紐付け
mode: "onChange", // バリデーションチェックのタイミングを設定
});
return (
<form className={styles.formWrapper} onSubmit={handleSubmit(onSubmit)}>
<h1>
プロフィール登録
</h1>
<div>
プロフィール登録に必要な情報をご入力ください。
</div>
<div className={styles.formItemWrapper}>
<label>ユーザーネーム</label>
<input {...register("username")} />
<span className={styles.formErrorMessage}>{formState.errors.username?.message}</span>
</div>
<div className={styles.formItemWrapper}>
<label>年齢</label>
<input {...register("age")} />
<span className={styles.formErrorMessage}>{formState.errors.age?.message}</span>
</div>
<div className={styles.buttonContainer}>
<button disabled={!formState.isValid}>登録</button>
</div>
</form>
);
};
参考
yup
yup - npm
react-hook-form + yup tips
【Next.js】React Hook FormとYupを使って入力フォームを実装してみた。
フォームのバリデーションに役立つYupとは? React向けライブラリを解説
React-hook-formとyupを使ったバリデーションの実装