Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yup conditional validation based on parent object schema

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),
});
like image 393
Ardneh Avatar asked Nov 04 '19 14:11

Ardneh


2 Answers

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")
  }),
});
like image 64
HGG-Dev Avatar answered Oct 04 '22 17:10

HGG-Dev


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.

like image 45
Abraham L Avatar answered Oct 04 '22 15:10

Abraham L