According to the official website, Zod is a TypeScript-first schema validation library with static type inference.
The goal is to eliminate duplicative type declarations. With Zod, you declare a validator once and Zod will automatically infer the static TypeScript type
Some other great aspects:
Zero dependencies
Works in Node.js and all modern browsers
Tiny: 8kb minified + zipped
Immutable: methods (e.g. .optional()) return a new instance
Concise, chainable interface
Functional approach: parse, don't validate
Works with plain JavaScript too! You don't need to use TypeScript.
After defining our schema, we use it to validate the shape of any data passed into it.
If there are errors, it will throw a ZodError. For a more comprehensive guide on Zod errors and the ZodError type, I recommend reading the documentation.
To safely use our schema, it’s best to wrap it in a try-catch block:
If you don't want Zod to throw errors when validation fails. use .safeParse.
This method returns an object containing either the successfully parsed data or a ZodError instance containing detailed information about the validation problems.
Let’s use Zod to validate the form's data
A common issue with Zod is that an empty string is valid as a type string, the fix for this would be specifying a minimum length of 1 and by default, all values are required
The provided code is an example from the Next.js learning resource.
The useFormState hook is used to manage the form state.
The form has an action attribute set to the dispatch function obtained from the useFormState hook.
The state object (state) contains messages and errors.
There is an input field for entering the invoice amount. It accepts numeric values and allows decimal numbers.
The errors are mapped for displaying validation errors related to the amount field.
useFormState Hook is currently only available in React’s Canary and experimental channels.
it allows you to update the state based on the result of a form action.
We're defining a React component (Form) for creating invoices. The form has an input field for the invoice amount, validated using a Zod schema (FormSchema).
The createInvoice function manages form validation, returns errors if any, and prepares validated data for potential database insertion.
Zod has become a handy tool for developers dealing with form validation, especially when combined with TypeScript.
Using Zod's schema declaration and validation features, developers can ensure that the data entered into forms aligns with the specified structure and adheres to predefined validation rules.