I encountered a similar issue and successfully utilized this workaround.
Tip: Provide the entire 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
}),
}),
});
Utilizing Context
Without Formik
Include your Form data as a context during validation
schema.validateSync(data, {context: form_data})
With Formik
Use validate instead of validationSchema
Pass your Form data as the 4th argument in validateYupSchema, representing context that can be accessed later in the schema.
Provide your schema as the 2nd argument in validateYupSchema.
<Formik
validate={(value) => {
try {
validateYupSchema(value, schema, true, value);
} catch (err) {
return yupToFormErrors(err); //for rendering validation errors
}
return {};
}}
onSubmit={} />
The following pertains to 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={} />