Hi there. Sorry if this is already included, but I can't find any documentation or issues regarding it.
I'm looking for a way to validate that a given type is one of multiple possible types. In FP, it would look like number | string, for example. React PropTypes offers this as oneOfType. I think yup would probably have either oneOfType or .or as in .string().or(yup.number()).
Is anything like this supported?
It looks like Joi has this as .alternatives as in Joi.alternatives().try([Joi.number(), Joi.string()]).
we don't have anything like alternatives due to a few ways in which yup is different than joi. However you can definitely use lazy to dynamically return a new schema type based on a value or other context
@jquense Could you please provide a basic example?
something like?
const schema = yup.lazy(value => typeof value === 'number' yup.number() : yup.string())
Using lazy is not ideal, because you have to write logic to check the value type before determining which validator to use. :/
@rivertam @Aaronius @sublimeye I hit against this issue as well (among others) so I made a validation library that supports it: https://github.com/vriad/zod
Specifically, there is a built-in "union" type, like so:
const numOrString = z.union([ z.string(), z.number() ])
Most helpful comment
@rivertam @Aaronius @sublimeye I hit against this issue as well (among others) so I made a validation library that supports it: https://github.com/vriad/zod
Specifically, there is a built-in "union" type, like so: