I had a form where I needed to enter the passphrase
if it was required and make it optional if it wasn't required. While validating the field using Yup I needed a way to conditionally change the validation logic for the field. For this, we need to use the when()
function from Yup which allows us to change the validation logic applied to a field based on some conditions.
Sample code:
<Formik
initialValues={initialValues}
validationSchema={Yup.object({
passphrase: Yup.string().when([], {
is: () => passwordRequired && !showMessage,
then: Yup.string().required("Passphrase is required"),
otherwise: Yup.string().notRequired(),
}),
})}
>
{/* ... */}
</Formik>
References:
Top comments (1)
Thank you!
I was searching for a way to create schema based in user configuration for required fields in a form.