Replies: 1 comment
-
|
One way to approach this is to use an explicit discriminated union. Not sure if the requirement is that if it's const offerIsAvailable = z.object({
isOfferAvailable: z.literal(true),
offerNotAvailableReason: z.undefined()
});
const offerNotAvailable = z.object({
isOfferAvailable: z.literal(false),
offerNotAvailableReason: z.string().min(1)
});
const schema = z.discriminatedUnion("isOfferAvailable", [
offerIsAvailable,
offerNotAvailable
]);
test("valid", (t) => {
t.true(schema.safeParse({ isOfferAvailable: true }).success);
t.true(
schema.safeParse({
isOfferAvailable: false,
offerNotAvailableReason: "It's around here somewhere..."
}).success
);
t.end();
});
test("invalid", (t) => {
t.false(
schema.safeParse({
isOfferAvailable: true,
offerNotAvailableReason: "Oh no!"
}).success
);
t.end();
}); |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
I have the following schema:
So what i want here is, when
isOfferAvailableistrue, thenofferNotAvailableReasonshould be required and also not be empty. I've read in other discussions here that i should userefine. But then i have to define the refinement on the root schema object and i can't set an error message on theofferNotAvailableReasonfield directly.In
yupthere iswhen, where i can access another value from the schema, how can i achieve this withzod?Sorry if this has been asked before, i searched through the discussions and issues and couldn't find anything which solved my problem. Thx in advance!!
Beta Was this translation helpful? Give feedback.
All reactions