Z
Zod15mo ago
Scott Trinh

Multistep Validation

I've come across cases where you want to check that things have some minimum amount of structure, and throw if it doesn't, but then conditionally catch any further refinements and handle those differently. For instance, I had an application where we were passing messages that had a defined type { type, payload } and if the request didn't match that shape, it would throw. However, we added new messages from time to time, so we wanted to just log a message if the type was unknown and return. In that case, I had two schemas: the "shape" schema, and the union of expected messages. I threw if it failed the shape parsing, but just logged a warning and skipped processing if the payload had an unexpected type, for instance.
2 Replies
Unknown User
Unknown User15mo ago
Message Not Public
Sign In & Join Server To View
Scott Trinh
Scott TrinhOP15mo ago
Sure! Not exactly sure what you have in mind, but here's an example (feel free to supply your own example that is closer to your actual use case):
const Schema = z.object({
foo: z.object({
bar: z.string(),
}),
baz: z.number(),
});

const StricterSchema = Schema.extends({
foo: Schema.shape.foo.extends({
bar: z.string().url(), // or Schema.shape.foo.shape.bar.url(), but that seems unnecessary in this trivial case
}),
});
const Schema = z.object({
foo: z.object({
bar: z.string(),
}),
baz: z.number(),
});

const StricterSchema = Schema.extends({
foo: Schema.shape.foo.extends({
bar: z.string().url(), // or Schema.shape.foo.shape.bar.url(), but that seems unnecessary in this trivial case
}),
});
Want results from more Discord servers?
Add your server