fastify-zod
fastify-zod copied to clipboard
about zod customize some error messages when creating a schema.
When I created zod schema, I customized some error messages for verification. But when I tried to verify, the custom error message didn't work.
code
user.scheme.ts
const loginSchema = z.object({
email: z
.string()
.email({ message: "Please enter the correct email address" }),
password: z.string(),
});
export const { schemas: userSchemas, $ref } = buildJsonSchemas({
....
loginSchema,
});
user.route.ts
async function userRoutes(server: FastifyInstance) {
server.post(
"/login",
{
schema: {
body: $ref("loginSchema"),
response: {
200: $ref("loginResponseSchema"),
},
},
},
loginHandler
);
}
app.ts
for (const schema of [...userSchemas, ...productSchemas]) {
server.addSchema(schema);
}
Send a request
{"email":"ad12dadasda","password":""}
response
{
"statusCode": 400,
"error": "Bad Request",
"message": "body.email should match format \"email\""
}