Last active
August 28, 2022 00:46
-
-
Save omar-dulaimi/866e7137510cc63337ad39b4632b1d9a to your computer and use it in GitHub Desktop.
Yup validate multiple schemas for the same field (Joi alternatives)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.