MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
Input Validation & Data Sanitization with Joi or Zod0%
Study Materials
Node.js & Express.jsProgress 0%
1.1Node.js Architecture, V8 Engine & Single-Threaded Event Loop1.2Call Stack, Callback Queue, Microtask Queue & Libuv Workers1.3Non-Blocking Asynchronous Code with Promises and Async/Await
5.1Input Validation & Data Sanitization with Joi or Zod5.2User Authentication with JWT (JSON Web Tokens) & HTTP-Only Cookies5.3Password Hashing with Bcrypt & Role-Based Access Control (RBAC)5.4Security Hardening: Helmet, CORS, Express Rate Limiting & HPP5.5Production Configuration, Environment Variables & PM2 Process Manager
HomeTutorialsNode.js & Express.jsInput Validation & Data Sanitization with Joi or Zod
User Authentication with JWT (JSON Web Tokens) & HTTP-Only Cookies

Input Validation & Data Sanitization with Joi or Zod

Beginner12 min read•Updated: 2026-11-18•By Er. Sumit Kumar (MSK Institute)
Study MaterialsCheatsheet

Never trust client input. Accepting unsanitized, unvalidated data directly into database queries or business operations leads to SQL/NoSQL injection, cross-site scripting (XSS), prototype pollution, and application crashes. In modern Node.js and TypeScript architectures, Zod has emerged as the premier schema validation library.


1. Why Zod?

  • TypeScript-First: Static type inference is derived directly from the runtime schema (z.infer<typeof schema>), eliminating duplicate type declarations.
  • Zero Dependencies: Extremely fast, lightweight, and works seamlessly on both Node.js backends and browser frontends.
  • Composable & Declarative: Intuitive chainable validators for strings, numbers, arrays, and nested objects.

2. Defining a Zod Validation Schema

1import { z } from 'zod';
2 
3export const registerUserSchema = z.object({
4 body: z.object({
5 username: z
6 .string({ required_error: 'Username is required' })
7 .min(3, 'Username must be at least 3 characters')
8 .max(30, 'Username cannot exceed 30 characters')
9 .regex(/^[a-zA-Z0-9_]+$/, 'Username can only contain letters, numbers, and underscores'),
10
11 email: z
12 .string({ required_error: 'Email is required' })
13 .email('Invalid email address format')
14 .toLowerCase()
15 .trim(),
16 
17 password: z
18 .string({ required_error: 'Password is required' })
19 .min(8, 'Password must be at least 8 characters')
20 .regex(/[A-Z]/, 'Password must contain at least one uppercase letter')
21 .regex(/[0-9]/, 'Password must contain at least one number'),
22 
23 age: z
24 .number()
25 .int()
26 .min(18, 'Must be at least 18 years old')
27 .optional()
28 })
29});

3. Creating a Reusable Validation Middleware

1// src/middleware/validate.js
2export const validate = (schema) => async (req, res, next) => {
3 try {
4 // Validate params, query, and body against the schema
5 const parsed = await schema.parseAsync({
6 body: req.body,
7 query: req.query,
8 params: req.params
9 });
10 
11 // Replace req properties with clean, sanitized, coerced data
12 req.body = parsed.body;
13 req.query = parsed.query;
14 req.params = parsed.params;
15 
16 next();
17 } catch (error) {
18 if (error.name === 'ZodError') {
19 const formattedErrors = error.errors.map(err => ({
20 field: err.path.join('.').replace('body.', ''),
21 message: err.message
22 }));
23 
24 return res.status(400).json({
25 status: 'fail',
26 message: 'Validation failed',
27 errors: formattedErrors
28 });
29 }
30 next(error);
31 }
32};

4. Applying Validation to Routes

1import { Router } from 'express';
2import { validate } from '../middleware/validate.js';
3import { registerUserSchema } from '../schemas/user.schema.js';
4import { registerUser } from '../controllers/auth.controller.js';
5 
6const router = Router();
7 
8// Route is protected: invalid payloads are rejected BEFORE hitting the controller!
9router.post('/register', validate(registerUserSchema), registerUser);
10 
11export default router;

Interactive Quiz• Knowledge Check

Multiple Choice Questions

Question 1
What is the primary advantage of validating request input with a library like Zod or Joi before hitting the controller?
Question 2
How can TypeScript types be inferred directly from a Zod schema without writing manual interfaces?
Question 3
Which HTTP status code is standard when a request payload fails schema validation rules?
Question 4
What does the .trim() and .toLowerCase() transformers on a Zod string accomplish?
Question 5
What method on a Zod schema validates data asynchronously and throws a ZodError if validation fails?

Next Lesson

User Authentication with JWT (JSON Web Tokens) & HTTP-Only Cookies

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
Global Error Handling Middleware & Custom AppError ClassesUser Authentication with JWT (JSON Web Tokens) & HTTP-Only Cookies

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master Node.js & Express.js with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext