Jump into concepts and practice - no test required
or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Schema validation in Express
📖 Scenario: You are building a simple Express server that accepts user data via a POST request. To keep your server safe and reliable, you want to check that the data sent by users matches the expected format before processing it.
🎯 Goal: Build an Express server that validates incoming JSON data against a schema using a middleware function. The server should only accept requests where the data matches the schema.
📋 What You'll Learn
Create an Express app with a POST route at /users
Define a schema object that requires name as a string and age as a number
Write a middleware function called validateUser that checks the request body against the schema
Use the validateUser middleware in the /users route to accept only valid data
💡 Why This Matters
🌍 Real World
Validating user input on a server is essential to prevent errors and security issues. This project shows how to do basic validation in Express before processing data.
💼 Career
Backend developers often write validation middleware to ensure APIs receive correct data. This skill is fundamental for building reliable and secure web services.
Progress0 / 4 steps
1
Set up Express app and user schema
Create an Express app by requiring express and calling express(). Then create a constant called userSchema that is an object with keys name set to "string" and age set to "number".
Express
Hint
Use require('express') to import Express and express() to create the app. Define userSchema as an object with the exact keys and string values.
2
Add JSON body parsing middleware
Add the Express middleware to parse JSON request bodies by calling app.use(express.json()).
Express
Hint
Use app.use(express.json()) to enable JSON parsing for incoming requests.
3
Create the validateUser middleware function
Write a middleware function called validateUser that takes req, res, and next as parameters. Inside, check that req.body.name is a string and req.body.age is a number. If valid, call next(). Otherwise, respond with status 400 and JSON message { error: "Invalid user data" }.
Express
Hint
Check the types of req.body.name and req.body.age using typeof. Call next() if valid, else send a 400 error response.
4
Add POST /users route with validation middleware
Add a POST route at /users using app.post. Use the validateUser middleware for this route. In the route handler, respond with JSON { message: "User data is valid" }.
Express
Hint
Use app.post with the path '/users', add validateUser as middleware, and send a JSON success message in the handler.
Practice
(1/5)
1. What is the main purpose of schema validation in an Express app?
easy
A. To store data permanently in the database
B. To speed up the server response time
C. To style the user interface automatically
D. To check if incoming data matches expected rules before processing
Solution
Step 1: Understand schema validation role
Schema validation ensures data received matches rules like type and format.
Step 2: Identify main purpose in Express
It prevents bad data from causing errors or security issues by checking before use.
Final Answer:
To check if incoming data matches expected rules before processing -> Option D
Quick Check:
Schema validation = data check before use [OK]
Hint: Schema validation means checking data fits rules before use [OK]
Common Mistakes:
Thinking validation speeds up server
Confusing validation with UI styling
Assuming validation stores data
2. Which of the following is the correct way to define a Joi schema for a required string named username?
easy
A. const schema = Joi.object({ username: Joi.string().required() });
B. const schema = Joi.string().required();
C. const schema = Joi.string().optional();
D. const schema = Joi.number().required();
Solution
Step 1: Recall Joi schema structure for objects
Joi schemas for objects use Joi.object({ key: rule }) format.
Step 2: Check correct rule for required string property
Property username must be a string and required, so use Joi.string().required().
Final Answer:
const schema = Joi.object({ username: Joi.string().required() }); -> Option A
B. It validates only the email string, not the whole object
C. It uses res.send instead of res.json
D. It should use Joi.number() for email
Solution
Step 1: Check what is validated
The schema expects an object with an email property, but code validates req.body.email (a string).
Step 2: Understand Joi object validation
To validate the whole object, pass req.body to schema.validate, not just one property.
Final Answer:
It validates only the email string, not the whole object -> Option B
Quick Check:
Validate whole object, not single property [OK]
Hint: Validate req.body object, not a single field string [OK]
Common Mistakes:
Validating only a property instead of full object
Confusing res.send and res.json (both work)
Forgetting to call next() is not required here
Using wrong Joi type for email
5. You want to validate a user object with optional phone that must be a string of 10 digits if present, and a required name string. Which Joi schema correctly enforces this?
hard
A. Joi.object({ name: Joi.string().required(), phone: Joi.string().pattern(/\d+/).required() })
B. Joi.object({ name: Joi.string(), phone: Joi.number().length(10).optional() })
C. Joi.object({ name: Joi.string().required(), phone: Joi.string().pattern(/^\d{10}$/).optional() })
D. Joi.object({ name: Joi.string().required(), phone: Joi.string().length(10).required() })
Solution
Step 1: Identify required and optional fields
Name is required string; phone is optional string matching exactly 10 digits.
Step 2: Check regex pattern and optional usage
Pattern /^\d{10}$/ matches exactly 10 digits; phone is optional, so use .optional().
Step 3: Eliminate incorrect options
Other options make phone required, use wrong types like Joi.number(), apply invalid methods like .length(10) on numbers, or use loose patterns like /\d+/.
Final Answer:
Joi.object({ name: Joi.string().required(), phone: Joi.string().pattern(/^\d{10}$/).optional() }) -> Option C