I came through similar issue. I used this workthrough with success.
Idea: Pass whole form-data as a context to the schema and access any form value using
this.options.context
const schema = yup.object().shape({
enabled: yup.boolean(),
contactDetail: yup.object().shape({
phoneNumber1: yup.string().nullable(),
phoneNumber2: yup.string().nullable(),
email: yup.string().test('email', 'test', async function () {
// this.options.context.enabled
}),
}),
});
Passing Context
Without Formik
Send your Form data as a context while validating
schema.validateSync(data, {context: form_data})
With Formik
Use validate instead of validationSchema
Pass your Form data as 4th argument in validateYupSchema which represents context and can be accessed later in schema.
Pass your schema as 2nd argument in validateYupSchema.
<Formik
validate={(value) => {
try {
validateYupSchema(value, schema, true, value);
} catch (err) {
return yupToFormErrors(err); //for rendering validation errors
}
return {};
}}
onSubmit={} />
Following is for the asynchronous validation with Formik.
<Formik
validate={async (value) => {
try {
await validateYupSchema(value, schema, false, value);
} catch (err) {
return yupToFormErrors(err); //for rendering validation errors
}
return {};
}}
onSubmit={} />