drizzle-zod is not sending custom message upon validation

I have created the following loginValidationSchema which I call in a validateData middleware inside my routes. I was expecting the custom error message to be sent to user whenever the user does not provide a value but it is not working \ zod-schema
export const loginUserSchema = createSelectSchema(user, {
email: (schema) =>
schema.min(1, 'Email is required').email('Email must be valid'),
password: (schema) => schema.min(1, 'Password is required'),
}).pick({
email: true,
password: true,
});
export const loginUserSchema = createSelectSchema(user, {
email: (schema) =>
schema.min(1, 'Email is required').email('Email must be valid'),
password: (schema) => schema.min(1, 'Password is required'),
}).pick({
email: true,
password: true,
});
//Routes
router.post('/login', validateData(loginUserSchema), loginUser);
router.post('/login', validateData(loginUserSchema), loginUser);
//Middleware
export default function (schema: AnyZodObject) {
return (req: Request, res: Response, next: NextFunction) => {
try {
schema.parse(req.body);
next();
} catch (error) {
if (error instanceof ZodError) {
const message = error.issues.map(
(issue) =>
`${
typeof issue.path[0] === 'string' ? issue.path[0] : 'Unknown-path'
}: ${issue.message}`
);
res.status(400).json({ error: message });
return;
} else {
throw error;
}
}
};
}
export default function (schema: AnyZodObject) {
return (req: Request, res: Response, next: NextFunction) => {
try {
schema.parse(req.body);
next();
} catch (error) {
if (error instanceof ZodError) {
const message = error.issues.map(
(issue) =>
`${
typeof issue.path[0] === 'string' ? issue.path[0] : 'Unknown-path'
}: ${issue.message}`
);
res.status(400).json({ error: message });
return;
} else {
throw error;
}
}
};
}
When a user forgets to send email when using the login route, I was expecting the error message to be 'email: Email is required' but I am receiving 'email: Required' instead. Why is this happening?
1 Reply
Antonio1337
Antonio13373d ago
I believe 'email: Email is required' happens only if the string doesn't have a minimum length of 1, not when the email is missing as a key. Basically, the difference between email: "" and email being undefined
Want results from more Discord servers?
Add your server