For someone used to working with Joi, this syntax is something I'm very familiar with:
title: Joi.alternatives().try(
Joi.string(),
Joi.object(SchemaObject)
)
But unfortunately it is not supported in Yup out of the box.
So, I figured out a way to make this work.
First, we need to add a new method to Yup:
yup.addMethod(yup.MixedSchema, "oneOfSchemas", function (schemas: Yup.AnySchema[]) {
return this.test(
"one-of-schemas",
"Not all items in ${path} match one of the allowed schemas",
(item) =>
schemas.some((schema) => schema.isValidSync(item, { strict: true }))
);
});
Then, we can use it as follows:
title: yup
.mixed()
.oneOfSchemas([
yup.string(),
yup.object().noUnknown().shape(SchemaObject2),
]);
That's all!
Top comments (0)