Facebook Pixel

How do I validate an ObjectId with Zod?

z.string().length(24) for a 24-char hex string (MongoDB ObjectId format). For stricter validation, use a regex: z.string().regex(/^[0-9a-fA-F]{24}$/). Zod will reject anything that does not match.

Verify This Answer

Cross-check this information using these trusted sources:

More FAQs in Input Validation With Zod in Express: A Complete Guide

Define a Zod schema, write a validate(schema) middleware factory that uses safeParse, returns 400 with errors if invalid, replaces req.body with parsed data if valid, and calls next. Apply per route: router.post('/signup', validate(signupSchema), signup).

TypeScript inference, great error messages, composable schemas, safe parse (returns success or error instead of throwing), and built-in types and transforms. It is one of the best modern validators for Node.js.

Use a separate factory that reads req.params. Example: const idSchema = z.object({ id: z.string().length(24) }); router.get('/users/:id', validateParams(idSchema), getUser). Validate query the same way with a validateQuery factory.

Still have questions?

Browse all our FAQs or reach out to our support team

Want to upskill yourself?

Our courses are taking a Coffee break, but your curiosity shouldn't. Stay engaged with namastedev linkedin, youtube, discord and other resources while you wait.

0
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.