Yup validation for 2+ inputs that are dependent

Viewed 785

I am using yup with formik for managing my form. I use yup for form validation. The problem I am facing is: say I have three fields fieldA, fieldB and fieldC. The validation is: fieldA + fieldB must be equal to fieldC. Here is what I have done using .when but I cannot add a [string, string, string] to the second parameter of yup.object().shape function.

yup.object().shape({
    
    fieldC: yup.number().nullable(),
    fieldA: yup.number().nullable()
      .when(['fieldA','fieldB', 'fieldC'], {
        is: (fieldA, fieldB, fieldC)=> // my condition //,
        then: // schemma //,
        otherWise: // schemma //,
      }),
   fieldB: yup.number().nullable()
       .when(['fieldA','fieldB', 'fieldC'], {
        is: (fieldA, fieldB, fieldC)=> // my condition //,
        then: // schemma //,
        otherWise: // schemma //,
      }),
  }, [['fieldA', 'fieldB','fieldC' ]]);
1 Answers

Thanks to this answer. Here is what I have done using test function.

    fieldC: yup.number().nullable(),
    fieldA: yup.number()
      .nullable()
      .test('fieldA-validation', 'invalid value', (value, context) => {
        return context.parent.fieldC === (context.parent.fieldB + value)
      }),
    fieldB: yup.number().nullable()
    .test('fieldB-commission-validation', 'invalid value', (value, context) => {
      return context.parent.fieldC=== (context.parent.fieldA + value)
    })
Related