Lesson
Create Custom Zod Schemas and Validate project-specific data
Create custom validation logic in Zod using z.custom, for primitive values, ensuring type safety and proper error messages for room numbers.
- Access
- Included
- Transcript
- Needs source
In this less we create a custom Zod schema using z.custom.
The example case covers room numbers validation: it must start with an uppercase letter followed by three digits. z.custom allows the creation of a brand new custom schema with a callback function that returns a boolean indicating validity.
We highlight a challenge with type inference in Zod's custom schemas: callback parameter types don't get aligned automatically - type-safety must be explicitly defined using type parameters.
We run tests against various room numbers and demonstrate how to effectively validate inputs and manage error messages.