Validate multiple fields against each other using Zod
See original GitHub issueIt’s common to validate fields based on other fields. For example, a form with a start date and end date.
The way to do this with Zod (that I know of) is like the snippet below. However, typescript will complain because validator will only accept a schema of type ZodObject, whereas here the schema is of type ZodEffects.
export const schema = z
.object({
start: z.date(),
end: z.date(),
})
.refine((val) => val.start < val.end, {
path: ['start'],
message: 'Start date must be before end date',
})
.refine((val) => val.start < val.end, {
path: ['end'],
message: 'End date must be after start date',
});
const { form } = createForm({
// ...
validate: validateSchema(schema)
// ...
});
I’ve had some success with manually casting like below. It doesn’t seem to work all the time though. Some of my forms fail to validate properly even when doing this. Not sure why yet.
- validate: validateSchema(schema),
+ validate: validateSchema(schema as z.AnyZodObject),
Issue Analytics
- State:
- Created 2 years ago
- Comments:5 (3 by maintainers)
Top Results From Across the Web
Require one of two fields · Issue #61 · colinhacks/zod - GitHub
I have large schema that needs to require one or another field. A nested partial Zod object with superRefine works for this (as...
Read more >Validate related schema attributes with Zod
Zod is a TypeScript-first schema declaration and validation library. I'm using the term "schema" to broadly refer to any data type, from a ......
Read more >At least one / minimum one field in Zod Schema Validation
I noticed there was custom parsing for the object id and the password. I think those could both be done with refine as...
Read more >Validate All the Things with Zod - Atomic Spin
Zod allows us to define a schema, infer types from that schema, then validate based on that schema. If the data doesn't match...
Read more >Schema validation in TypeScript with Zod - LogRocket Blog
In this article, you will learn about schema design and validation in Zod and how to run it in a TypeScript codebase at...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Thanks for the issue regardless! I did fix the type of the expected schema, so you shouldn’t need to cast the value on the latest version.
https://github.com/colinhacks/zod/issues/479
I should’ve done a better job searching. It seems like this is how zod works. There are a few workarounds in that thread as well.