jquense / yup

Dead simple Object schema validation
MIT License
22.86k stars 932 forks source link

Conditional validation between different objects #2239

Open clouds83 opened 2 months ago

clouds83 commented 2 months ago

I'm creating a pretty complex form using RHF and Yup for validation, and I need to add a conditional validation in a field, based in a field that lives outside the object of this field.

I searched extensively for a solution, but I couldn't find one. For conditional validation within the same level works fine.

securityDetails: yup.array().of(
  yup.object().shape({
    listingDetails: yup.object().shape({
      investorNoteEn: yup.string(),
      investorNoteFr: yup.string().when('investorNoteEn', {
        is: (value) => !!value,
        then: (value) => value.required('Please complete this field in both English and French before submitting.'),
        otherwise: (value) => value.optional(),
      }),
    }),

    marketCapitalization: yup.object().shape({
      totalEquity: yup.string().when('investorNoteEn', {
        is: (value) => {
          console.log(value)
          return !!value
        },
        then: (value) => value.required('Total equity is required'),
        otherwise: (value) => value.optional(),
      }),
    }),
  }),
),

The first object, listingDetails, has a conditional validation that works fine, but the second that has pretty much the same validation conditioned by the same investorNoteEn field, doesn't work.

I tried the following approaches:

Does anyone know a way to achieve that?

Thanks in advance.

LeonardoSousa20 commented 2 months ago

Hi, I'm in the same situation, did you manage to find a solution to this problem?