Reputation: 408
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
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