0

I am running into this issue with Formik Validation Schema. My form has 3 shapes it takes and a few fields that are present in each shape depending on the given params type and upperType. The issue is when I try submit my form if one of the below fields in not visible and doesn't have a value the submitForm function doesn't fire. I've set the conditional logic as best I think I can so why is .nullable not allowing form submission?

examples of form shape:

type === expire => only endDate

type === permanent => lower & upper(depending on upperType) & startDate

etc.

The issue is when only endDate is visible the form still tries to validate the rest of the form fields and same with the other shapes of the form. Is my validation logic incorrect?

export const validationSchema = (type: string, upperType: RangeType | undefined) => {
  const result = Yup.object({
    lower: Yup.string().when([], {
      is: type !== 'expire',
      then: Yup.string().required(errorMessages.lowerRequired),
      otherwise: Yup.string().nullable(true)
    }),
    upper: Yup.string().when([], {
      is: (type !== 'expire' && (upperType === ASYMMETRICAL || upperType === OUTER)),
      then: Yup.string().required(errorMessages.upperRequired),
      otherwise: Yup.string().nullable(true)
    }),
    startDate: Yup.date()
      .when([], {
        is: type === 'permanent' || type === 'temporary',
        then: Yup.date().nullable(true)
      })
      .max(dateMaxServer(), errorMessages.dateMax),
    endDate: Yup.date().when([], {
      is: type === 'temporary' || type === 'expire',
      then: Yup.date().required(errorMessages.dateRequired),
      otherwise: Yup.date().nullable(true)
    }),
  })
  return result
}

Haq.H
  • 863
  • 7
  • 20
  • 47

1 Answers1

0

I think is expects function if you want to compare in a custom way .

is: type !== 'expire', //always resolves to **true** if it is used without function

Give it a try.

Replace

is: type !== 'expire'

to

is: ()=>type !== 'expire',
Dipesh KC
  • 2,273
  • 1
  • 15
  • 19