Skip to content

Yup validation: cyclic dependency error with multiple dependent fields

I’m using Yup to validate 3 fields which are all dependent on each other. fieldA, fieldB and fieldC. They are numbers and at least one of them needs to have a value > 0.

I’m trying to solve it like this:

myFields: Yup.object().shape(
  {
    fieldA: Yup.number().when(['fieldB', 'fieldC'], {
      is: (fieldB, fieldC) =>
        fieldB < 1 && fieldC < 1,
      then: Yup.number().min(
        1,
        'some error message'
      ),
    }),
    fieldB: Yup.number().when(['fieldA', 'fieldC'], {
      is: (fieldA, fieldC) =>
        fieldA < 1 && fieldC < 1,
      then: Yup.number().min(
        1,
        'some error message'
      ),
    }),
    fieldC: Yup.number().when(['fieldB', 'fieldA'], {
      is: (fieldB, fieldA) =>
        fieldB < 1 && fieldA < 1,
      then: Yup.number().min(
        1,
        'some error message'
      ),
    }),
    
  },
    ['fieldA', 'fieldB', 'fieldC']
),

This worked fine with only 2 fields fieldA and fieldB, where each one only had the other field passed in when(... but since introducing a third field, I now have a cyclic dependency. Do I need a completely different approach, ie. an external validation function or am I missing some detail here?

Answer

Your dependencies array is wrong, needs to be [[string, string]], hence you cannot bind all 3 of your fields inside. You have to do it in combinations as

[['fieldA', 'fieldB'], ['fieldA', 'fieldC'], ['fieldB','fieldC']]