Validation your data before it get in to your code is the clean way.
Data that came after validation will be more accurate than the normal data. Data can be manipulated in any way, so validation before any action is a secure choice.
There are some alternatives to Zod to validate your data with joi. You can see a comparation on their website. We will use Zod for now. Zod can be used with JavaScript and TypeScript. You can parse the data without doing any validation.
In this example, we will use Zod in the NodeJS project. We will need NodeJS.
After installing the NodeJS, you can create a node project with the command npm init -y
in your project folder. The node will generate the project for you.
To install Zod dependency, you can run this command: npm install zod
.
Zod will need Zod schema to define the data from you.
The Zod schema will be required by default.
We can do more with pre-build validation like Email, URL, etc.
And there are more than this in their docs
Match prefers to use custom schema with TypeScript rather than JavaScript.
You can create custom errors too.
There are 2 preferred ways to validate data with schema:
Parse will throw the error if the condition is not satisfied.
SafeParse method will return an object with success and data or error.
Transform data after parsing.
Customize your validation with the refine
method from Zod.
NOTE: From the document, Zod said:
⚠ Refinement functions should not throw. Instead they should return a falsy value to signal failure.
Zod also provides you with async functions.
An Example
This is just the surface of the Zod library. If you want more information, you can check out their docs.