Using .safeExtend() without repeating definitions #5393
Replies: 1 comment 1 reply
-
|
Hi @lukes-marvin-com! I'm Dosu and I’m helping the zod team. You can absolutely reuse your base schema's field definitions when extending with const formSchema = baseSchema.safeExtend({
role: baseSchema.shape.role.nonoptional('please provide a user type'),
projectType: baseSchema.shape.projectType.min(1, 'project type...')
});This pattern is supported and recommended for avoiding duplication and customizing error messages or required/optional status in extensions. You can also use spread syntax to build new schemas from shared shapes if you prefer that style. See the official docs and this discussion for more details. For your React Hook Form integration: if the checkbox group returns If this solves your question, feel free to close the issue! If you need more help, a minimal runnable reproduction is always welcome. To reply, just mention @dosu. How did I do? Good | Irrelevant | Incorrect | Verbose | Hallucination | Report 🐛 | Other |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Hi all, thanks for reading.
I have a base schema for api validation -
I am trying to safe extend this so I can benefit from the base schema role enum and projectType array types without having to repeat this logic, I just want to add error messaging and make it required. I want this because the api doesn't require the role or project necessarily and I might want to use this base schema elsewhere in another form that doesn't require a role input at all. So I don't want to add much to the base schema. Also the error message might be different elsewhere, so I think that safe extending off of a more general base schema without explicit error messages is required for me.
So this works:
But it would be super nice to do something like this (not have to use the same enum values) -
the project type is a form input of multiple checkboxes that get added to an array. The default value from react hook form comes in as false. I also realize I could provide a default value to react hook form but it would be nice to not have to.
Beta Was this translation helpful? Give feedback.
All reactions