jquense / yup

Dead simple Object schema validation
MIT License
22.94k stars 935 forks source link

How can I dynamically add or remove required fields in Yup? #2135

Closed mahmutoz closed 1 year ago

mahmutoz commented 1 year ago

I want the field "taxOffice" to be required or not based on the value received in the "membershipType" field. How can I achieve this using Yup?

"When I use the when() function, I encounter the following error: 'Uncaught (in promise) TypeError: branch is not a function.' I haven't been able to find a solution for this.

Yup version: 1.3.2"

const NewUserSchema = Yup.object().shape({
    company: Yup.object().shape({
      membershipType: Yup.string().required(),
      taxOffice: Yup.string().when('membershipType', {
        is: (val) => val === "GOVERNMENT_INSTITUTION",
        then: Yup.string().required(),
        otherwise: Yup.string(),
      }),
  }),
})
mahmutoz commented 1 year ago

I solved.

Solition:

const NewUserSchema = Yup.object().shape({
    company: Yup.object()
      .shape({
        membershipType: Yup.string().required(),
      })
      .when(([values], schema) => {

        if (values.membershipType === "GOVERNMENT_INSTITUTION") {
          return schema.shape({
            taxOffice: Yup.string().required(),
          })
        }

        return schema
      }),
  })