✨ Set a Default Value with Zod ✨
Our following example starts similarly to the last: a form input validator that supports an optional value.
This time, the Form has a repoName and an optional array of keywords:
const Form = z.object({
repoName: z.string(),
keywords: z.array(z.string()).optional(),
})
In order to make things easier for the actual form, we want to set this up so that an array of strings does not have to be passed in.
Zod’s .default schema method allows us to pass in a value if no other value is provided.
In this case, we will set it to an empty array with .default([]).
Before:
keywords: z.array(z.string()).optional()
After:
keywords: z.array(z.string()).default([])
Because we are adding a default value, we no longer need .optional() because optional is included within it.
const Form = z.object({
repoName: z.string(),
keywords: z.array(z.string()).default([])
})
I hope you found it useful. Thanks for reading. 🙏
Let's get connected! You can find me on:
Hashnode: https://nhannguyen.hashnode.dev/
X (formerly Twitter): https://twitter.com/nhannguyendevjs/