Skip to content

Instantly share code, notes, and snippets.

@omar-dulaimi
Last active August 28, 2022 00:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save omar-dulaimi/866e7137510cc63337ad39b4632b1d9a to your computer and use it in GitHub Desktop.
Save omar-dulaimi/866e7137510cc63337ad39b4632b1d9a to your computer and use it in GitHub Desktop.
Yup validate multiple schemas for the same field (Joi alternatives)
// First you define a method called `oneOfSchemas`
yup.addMethod(yup.MixedSchema, "oneOfSchemas", function (schemas) {
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 you use it as follows:
title: yup
.mixed()
.oneOfSchemas([
yup.object().noUnknown().shape(SchemaObject1),
yup.object().noUnknown().shape(SchemaObject2),
]);
// Inspired by https://gist.github.com/cb109/8eda798a4179dc21e46922a5fbb98be6
@itaym
Copy link

itaym commented Aug 28, 2022

Very nice, I just had to change lines 7/ 8 to:
(item) =>
schemas.reduce((bool, schema) => bool || schema.isValidSync(item, { strict: true}), false)
That it will be ok if one of the schemas validates.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment