zod
zod copied to clipboard
Provide value to lazy callback
Hey, first of all, thanks for Zod!
I'd like to access the value being validated inside a lazy
callback, like this:
z.lazy((value) => {
if (value) {
return z.object({
...
})
}
return z.object({
...
})
});
I can't use a zod union because there isn't a good way to use unions with Formik (https://github.com/robertLichtnow/zod-formik-adapter/issues/2).
This functionality would be similar to Yup's lazy
: https://github.com/jquense/yup#lazyvalue-any--schema-lazy
Thanks!
This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.
Bump.
This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.
Bump.
I wonder if z.custom
would work for your use case? Definitely doesn't feel as ergonomic as a union, but it's close to what you're looking for:
const customSchema = z.custom(
(value) => {
if (value) {
return z
.object({
// ...
})
.safeParse(value)
.success;
}
return z.object({
// ...
})
.safeParse(value)
.success;
}
);
(or however you want to deal with the runtime here). Like lazy
I think you'll have to provide the correct type and since you can't use a union, I'm not sure it'll be very easy to use, but maybe the types are the same in your case? Otherwise lazy
wouldn't work either. 🤔
Thanks @scotttrinh. I don't see any docs on z.custom
. Is that officially supported?
This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.
bump.
This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.
bump.
I don't see any docs on
z.custom
. Is that officially supported?
https://github.com/colinhacks/zod#custom-schemas
looks like the z.custom docs were just added a few weeks ago. https://github.com/colinhacks/zod/commit/2a6703a9c9daf8111ac1ebf4573f59f21039595d
four hours of searching and I finally land here to learn that my conversion from yup to zod is not going to go as smoothly as planned
I, too, would like zod.lazy() to receive the value in the callback