#Date issue in Zod with Express

6 messages · Page 1 of 1 (latest)

near trench
#

I always get Expected date, received string issue in Zod.

This is my Schema ```ts
export const Schema = z.object({
// Other fields !
datePublished: z.string().pipe(z.coerce.date()),
});

I use this middleware to validate the request body ```ts
export const validateBody =
  <T extends z.ZodType>(schema: T) =>
  async (req: Request, res: Response, next: NextFunction) => {
    try {
      await schema.parseAsync(req.body);
      next();
    } catch (error: any) {
      res.status(400).json({ error: error.issues });
    }
  };

What am I doing wrong here?

earnest mica
#

@near trench I think you'll need to give input that reproduces the issue; the schema itself seems fine

#
export const Schema = z.
  datePublished: z.string().pipe(z.coerce.date()),
});

// parses successfully
console.log(Schema.safeParse({
    datePublished: '2024-01-15T18:06:42.181Z'
}))
earnest mica
#

Well that works, too