Add a .message() method to Zod schemas for a default error message
#3094
-
Description:Currently, Zod allows us to specify error messages for each validation method like For example, consider this schema: const guestUserSchema = z.object({
name: z
.string({
invalid_type_error: "Invalid name",
required_error: "Name is required",
})
.min(3, {
message: "Name must be at least 3 characters long",
})
.max(20, {
message: "Name must be at most 20 characters long",
}),
username: z.string().min(3).max(20).startsWith("guest_"),
method: z.array(z.literal("guest")).default(["guest"]),
});I would like to be able to specify a default error message for the name field that is shown when any validation fails, like this: const guestUserSchema = z.object({
name: z
.string()
.min(3)
.max(20)
.message("Name must be between 3 to 20 characters"),
username: z.string().min(3).max(20).startsWith("guest_"),
method: z.array(z.literal("guest")).default(["guest"]),
});In this example, the .message() method would set a default error message for the name field that is shown when the min or max validation fails. Use Case:This feature would be useful for providing more general error messages when any validation fails for a field, instead of having to specify an error message for each validation method. Proposed Solution:Add a .message() method to Zod schemas that sets a default error message for a field. This message would be shown when any validation fails for the field. Alternatives Considered:An alternative is to use the |
Beta Was this translation helpful? Give feedback.
Replies: 4 comments 1 reply
-
|
Is this what you are looking for? const guestUserSchema = z.object( {
name: z
.string( { errorMap: () => ( { message: 'Name must be between 3 to 20 characters' } ) } )
.min( 3 )
.max( 20 )
} )If you found my answer satisfactory, please consider supporting me. Even a small amount is greatly appreciated. Thanks friend! 🙏 |
Beta Was this translation helpful? Give feedback.
-
|
Yeah, Exactly! 🔥❤️ |
Beta Was this translation helpful? Give feedback.
-
|
How can we do this using ZOD 4? errorMap doesnt exist anymore and error will not give us a default error message |
Beta Was this translation helpful? Give feedback.
-
|
Also using v4 and had the same issue |
Beta Was this translation helpful? Give feedback.
Is this what you are looking for?
If you found my answer satisfactory, please consider supporting me. Even a small amount is greatly appreciated. Thanks friend! 🙏
https://github.com/sponsors/JacobWeisenburger