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")
}),
});
Quite sure you've already found a solution/workaround. However this approach may come in handy for people coming to this very question for a potential solution:
Since you need the values of sibling fields for a schema that is nested, you could create the nested schema using when
, for example:
const schema = Yup.object().shape({
condition: Yup.boolean()
.required('Error'),
terms: mixed().when('condition',(value) => {
// use any logic you need to build/modify the returned schema
return array().of(termsSchema)
}),
});
Accessing nested fields using .when is a current limitation of yup, however this approach worked for me. I am also curious about what you did to solve this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With