I'm creating Yup validation schema with array().of method and I need to set some validation rules in that array based on value from outer schema object. How can I get reference to that value?
const termsSchema = Yup.object().shape({
termType: Yup.string().when('condition', {
is: true,
then: Yup.string()
.required('Type is required'),
}),
});
const schema = Yup.object().shape({
condition: Yup.boolean()
.required('Error'),
terms: Yup.array().of(termsSchema),
});
Variables from outside the Yup Schema can be access via a callback function using when. You can use any dummy field for the first parameter as the purpose was only to trigger the callback. Once condition is met, the validation rule after then would apply. For more information refer Yup.
let outside = true
const schema = Yup.object().shape({
dummy:Yup.string(),
terms: Yup.array().of(termsSchema).when("dummy", {
is: (value) =>
outside === true,
then: Yup.number().required("Please provide info")
}),
});