目次
環境ormik: version 2.2.9
動的バリデーションを実施する
例えばフォームで以下のようにチェックボックスがあって、チェックがついてるときのみ出現するフォームにバリデーションを行いたいとする。
ソースコードは以下の状態
<Formik
initialValues={{
email: "",
password: "",
other: "",
toggle: false,
checked: [],
}}
validationSchema={Yup.object({
email: Yup.string()
.email("Invalid email address")
.required("required"),
password: Yup.string().required("required"),
other: Yup.string().required("required"),
})}
onSubmit={(values) => alert("Form Completed")}
>
{(formik) => (
<Form>
<Stack width="50%" gap={3}>
<Field name="email" type="text" />
<ErrorMessage name="email" />
<Field name="password" type="password" />
<ErrorMessage name="password" />
<label>
<Field type="checkbox" name="toggle" label="test" />
その他項目
</label>
{formik.values.toggle && (
<div>
<Field name="other" type="text" />
<ErrorMessage name="other" />
</div>
)}
<Button variant="contained" type="submit">
Submit
</Button>
</Stack>
</Form>
)}
</Formik>
上記のソースコードは「その他項目」のチェックをつけるとその他の入力項目が出現するフォーム


何も考えないノーマル状態だと、非表示の項目にバリデーションがかかってしまいSubmitを押してもフォームが送信できなくなる。

解決方法
以下のようにvalidationSchemaの箇所でYup.string().when
を用いて、その他入力箇所はチェックボックスがtrueのときのみ実行されるように設定する。
validationSchema={Yup.object({
email: Yup.string()
.email("Invalid email address")
.required("required"),
password: Yup.string().required("required"),
other: Yup.string().when("toggle", {
is: true,
then: Yup.string().required("required"),
}),
})}
その他項目は以下の項目が入力されていなくてもフォームが送信できるようになる。

完了!
コメント