YUP validate object attribute based on other attributes of the same object

Viewed 607

I have a yup array of objects, and the shape of these objects are three string values. Each of these string values are required if any of the other two have been filled out. If all three are empty, none is required. The idea is that the array is optional, but if you want to insert values in it, you must insert all values in the object:

feesRanges: yup.array().of(
                yup.object().shape({
                    above: yup.string().required(),
                    fixedFee: yup.string().required(),
                    variableFee: yup.string().required(),
                })
            ),

My guess was that I had to to put a .when() in each of the values of the object, something like:

feesRanges: yup.array().of(
            yup.object().shape({
                above: yup.string().when(['fixedFee', 'variableFee'], {
                    is: (fixedFee: string, variableFee: string) => fixedFee || variableFee,
                    then: yup.string().required(),
                    otherwise: yup.string().notRequired(),
                }),
                fixedFee: yup.string().when(['above', 'variableFee'], {
                    is: (above: string, variableFee: string) => above || variableFee,
                    then: yup.string().required(),
                    otherwise: yup.string().notRequired(),
                }),
                variableFee: yup.string().when(['above', 'fixedFee'], {
                    is: (above: string, fixedFee: string) => above || fixedFee,
                    then: yup.string().required(),
                    otherwise: yup.string().notRequired(),
                }),
            })
        ),

But after I tried it, yup began giving me a cyclic error:

Error: Cyclic dependency, node was:"variableFee"

How can I make this reference, binding the requiredness, so to speak, of one object attribute to the others?

0 Answers
Related