DEV Community

Omar Dulaimi
Omar Dulaimi

Posted on

How to validate multiple schemas for the same field with Yup?

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)
  )
Enter fullscreen mode Exit fullscreen mode

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 }))
  );
});
Enter fullscreen mode Exit fullscreen mode

Then, we can use it as follows:

title: yup
  .mixed()
  .oneOfSchemas([
    yup.string(),
    yup.object().noUnknown().shape(SchemaObject2),
  ]);
Enter fullscreen mode Exit fullscreen mode

That's all!

Top comments (0)