T
TanStack•9mo ago
extended-salmon

Possible to update Zod schema and revalidate?

I have a toggle that makes an additional field required. I only want to validate it when the toggle is on. So I'm trying to merge in the additional Zod schema and validate against it. For this I have a useEffect (pictured) to listen for the toggle to change in form.store and merge an additional Zod schema. And it works! ...when I toggle it on. My otherwise valid form goes to canSubmit: false. However if I turn the toggle off it should be going back to the initial schema and validate the form. However this does not happen: the form stays in canSubmit: false and the fieldMeta for the unrequired field still displays an error. Am I thinking about this correctly? Should it be possible to swap out the schema and validate the form? Do I need to revalidate the whole form when I swap out the schema? Since the schema is changed by setState this should cause a rerender and a revalidate? Many many thanks, I've spent too many hours sweating over this. 🥹
No description
2 Replies
extended-salmon
extended-salmonOP•9mo ago
Is the recommended zod approach just to have one massive schema and do superRefine's to handle conditional validation? I was trying to only apply the zod schemas that matched the form's fields, but I guess I could have one massive schema that sets fields as optional unless they are toggled on.... :/
conscious-sapphire
conscious-sapphire•9mo ago
You need to use discriminatedUnions from Zod mate, this is not a tanstack-form thing

Did you find this page helpful?