DEV Community

Kazi Abdur Rakib
Kazi Abdur Rakib

Posted on

Implement validateRequest Middleware

const validateRequest = (Schema: AnyZodObject) => {
  return async (req: Request, res: Response, next: NextFunction) => {
    //validate

    // Validate
    try {
      await Schema.parseAsync({
        body: req.body,
      });
      next();
    } catch (err) {
      next(err);
    }
  };
};
router.post(
  '/create-student',
  validateRequest(studentValidations.studentValidationSchema),
  userControllers.createStudent,
);
Enter fullscreen mode Exit fullscreen mode
const studentValidationSchema = z.object({
  body: z.object({
    password: z.string().min(1),
    student: z.object({
      name: UserNameValidationSchema,
      gender: z.enum(['male', 'female', 'other']),
      dateofBirth: z.string(),
      email: z.string().email(),
      contactNo: z.string().min(1),
      emergenyContractNo: z.string().min(1),
      bloodGroup: z.enum(['A+', 'A-', 'B+', 'B-', 'AB+', 'AB-', 'O+', 'O-']),
      presentAddress: z.string().min(1),
      permanentAddress: z.string().min(1),
      guardian: GurdianValidationSchema,
      localguardin: LocalGuardianValidationSchema,
      profileImg: z.string().optional(),
    }),
  }),
});

Enter fullscreen mode Exit fullscreen mode

Top comments (0)