Skip to Content
πŸ“š TutorialπŸ”— Express Js6) Data Validations

Data Validations

The following guide will using zod for validating data.

1. Install zod

https://zod.dev/Β 

npm install zod

2. Validing body data

Lets create a scheme for defind the input body object

scheme.ts
import { z } from "zod"; export const currentUserScheme = z.object({ email: z.string(), name: z.string(), studentId: z.number() }) export type CurrentUser = z.infer<typeof currentUserScheme>; /* { email: string name: string studentId: number } */
server.ts
//... import { currentUserScheme, CurrentUser } from './scheme'; app.post('/register', async (req: Request, res: Response) => { try { // Will throw error is input body is not match the scheme const currentUser: CurrentUser = currentUserScheme.parse(req.body); console.log(currentUser); return res.status(200).json(currentUser); } catch (error) { return res.status(500).json(error); } });
Last updated on