-
Notifications
You must be signed in to change notification settings - Fork 934
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Option for one of the 2 schemas #662
Comments
@ankitjaincst This question was raised once in the past. You can find it here #69 Edit:
|
@jquense Is there a better way to do this? |
Update: I just had to do this thrice, so I just made a simple npm module to wrap up testing a(ny) yups: https://www.npmjs.com/package/@aibex/ayup If you're not concerned about async validation, you can utilize const yup = require("yup");
const ayup = tries => {
return yup.mixed().when(".", current => {
for (const t of tries) {
try {
t.validateSync(current, {
strict: true,
});
return t;
} catch (e) {} // discard
}
return yup.mixed().test(
"ayup-failure",
"No alternatives for ayup were successful",
v => false
);
});
};
const schema = yup.object().shape({
colors: ayup([yup.string(), yup.array().of(yup.string())])
}); Or alternatively, if you want to write it in a declarative way: const alternatives = yup.mixed(); // needed for multiple .when
alternatives.when({
is: v => typeof v === "string",
then: yup.string()
});
alternatives.when({
is: v => Array.isArray(v),
then: yup.array().of(yup.string())
});
const schema = yup.object().shape({
colors: alternatives
}); Personally, I feel the Edit: This may rely on a bug, as |
I was recently faced with this issue, this was my solution: const schemaA = mixed().test(). --whatever-- .required();
const schemaB = mixed().test(). --whatever-- .required();
const schemaAorB = mixed<InferType<typeof schemaA> | InferType<typeof schemaB>>()
.test("shape", "invalid", (data) => schemaA.isValidSync(data) || schemaB.isValidSync(data); |
I faced the same issue today, and this was my solution: const schemaA = yup().object().shape({}). --whatever-- .required();
const schemaB = yup().object().shape({}). --whatever-- .required();
const schemaAorB = yup.lazy(value => {
if (value.a) {
return schemaA
}
return schemaB
}) |
Describe the bug
I have a usecase where both of these are valid to me { colors: "red"} as well as {colors: ["red", "blue"]}
How can I implement something like one of 2 schemas . Eg . Yup.string() || Yup.array().string()
To Reproduce
Provide a running code snippet in using https://repl.it/@jquense/yup or similar
Expected behavior
A clear and concise description of what you expected to happen.
Platform (please complete the following information):
Additional context
Add any other context about the problem here.
The text was updated successfully, but these errors were encountered: