MAYANK KUMAR
MAYANK KUMAR

Reputation: 408

How to write conditional required in yup

Hi I want to write a conditional schema in yup.

Here is the schema code:

  const Schema = yup.object({
currentLocation: yup
  .string()
  .required('Please enter the Current Location.'),
hometown: yup.string().required('Please enter your HomeTown Location.'),
phoneNumber: yup
  .array()
  .of(yup.string())
  .required('Please enter your Phone Number'),
whatsappNumber: yup
  .array()
  .of(yup.string())
  .required('Please enter your Phone Number'),
hasManager: yup.bool(),
managerName: yup.string(),
managerCompanyName: yup.string(),
managerEmail: yup.string(),
managerContact: yup.string(),
});

Now I want to managerName , managecompany.... managercontact to be required only if hasManager is true

How do i do it?

Upvotes: 2

Views: 862

Answers (1)

CD..
CD..

Reputation: 74156

You can use when, for example:

managerName: yup.string().when('hasManager', {
      is: true,
      then: yup.string().required(),
      otherwise: yup.string()
    }),

Or:

managerName: yup.string().when('hasManager', (hasManager, schema) => {
    return hasManager ? schema.required() : schema;
  }),

Upvotes: 3

Related Questions