Reputation: 330
I am using react with Vite, shadcn, RHF and zod. I have a multi step form and I need to get my forms in each step validated with zod. In my forms, I have inputs which are Select inputs whose values have been populated with array of objects initially. When the user selects an option, then an object gets selected. I am using await trigger() when moving to the next step to trigger validation. For starters, I have created a zod schema for the 1st form and I need to customize the message in errors object.
My first form's data structure is like this
"templateDefaults": [{
templateCode: {},
...
}, {
...
}]
This is my schema for the first form. Currently, I am just providing the templateCode key value and a true condition by default in superrefine(). I am getting the zod default message "Expected object, received array". Type is "invalid_type". How can I modify the message so that trigger() picks up the custom message instead of default?
const templateDefaultsSchema = z.array(
z.union([
z.object({
templateCode: z
.object({
tenantName: z.string(),
tenantId: z.number(),
})
.passthrough()
.superRefine((val, ctx) => {
if (1 == 1) {
ctx.addIssue({
code: z.ZodIssueCode.invalid_type,
message: "An option has to be selected",
});
}
}),
...
}),
z.object({
...
}),
])
)
Also, the path to the input is correct. It is currently like templateDefaults[0].templateCode. In superrefine or refine do I need to specify this path? or would just ["templateCode"] suffice?
Any help or suggestion would be greatly appreciated.
Upvotes: 1
Views: 162
Reputation: 529
To override the default error messages from zod
types (i.e. invalid_type
), you can optionally provide the errorMap
parameter; for example:
z.object( { errorMap: () => ( { message: '[message]' } ) } )
Per, https://github.com/colinhacks/zod/discussions/3094#discussioncomment-7984907
Upvotes: 1