Feature: Conditional Validation Similar to yup.when()
See original GitHub issueSimilar to this Yup issue: https://github.com/jquense/yup/issues/176 and creating a new issue out of #61.
Many users of zod would like to do conditional requirement or validation of fields based on either fields passed as context to zod, or based off of the value of another schema property. This is common to do in form validations.
The closed issue #61 addresses how to do conditional validation with superRefine
. This works well enough in small cases, but many folks have large complex schemas and we would like to keep the existing validation on an object i.e. not have to make the entire object partial in order for conditional requirement to work.
This issue stems from the reaction to my comment https://github.com/colinhacks/zod/issues/61#issuecomment-1171958123
Pasting from the comment as my case is the same:
I have large schema that needs to require one or another field. A nested partial Zod object with superRefine
works for this.
What I want to be able to do however, is to do conditional requirement on 1 or 2 fields without making the entire object partial and while having access to all of the fields in the object.
Ex: I have a required enum that has two values: “ValueA” and “ValueB”
Upon “ValueA” then someOtherFieldA is required. Upon “ValueB” then someOtherFieldB is required.
There are also other required fields within the schema that should remain required without explicitly checking them in something like superRefine
.
The reason I chose zod over yup was TypeScript support, but in yup’s beta versions TS support has improved a lot. Not having a functionality like this is a big blocker for me wanting to keep using zod. Thanks!
Issue Analytics
- State:
- Created a year ago
- Reactions:122
- Comments:13 (2 by maintainers)
Top GitHub Comments
This is currently the only problem I have with zod - I have to do conditional field validation in superRefine which is not the problem but then if I want to use that schema in other places with
extend()
ormerge()
the problem starts.I think that something like
yup.when()
is the only missing part in this schema validation library.Thanks for the response @deniskabana. The problem is that these refinements shouldn’t live inside the
ZodDate
instance. They should get attached to theZodObject
schema that containsstartDate
andendDate
. Let me know if I’m still misunderstanding.Note that you actually have typing on
startDate
andendDate
because this approach doesn’t try to break locality, unlike the Yup example, in which Yup has no idea what the type should be on those values. Way less verbose and more typesafe. UsesuperRefine
if you want to customize error codes or messages.You can also define this refinement as a separate function and drop it into multiple schemas.