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
Validating body fields
📖 Scenario: You are building a simple Express server that accepts user data through a POST request. To keep your server safe and reliable, you need to check that the user sends the right information in the request body.
🎯 Goal: Create an Express server that validates the name and email fields in the request body before processing the data.
📋 What You'll Learn
Create an Express app
Add middleware to parse JSON request bodies
Check that the name field exists and is a string
Check that the email field exists and contains an '@' symbol
Send a 400 error response if validation fails
Send a 200 success response if validation passes
💡 Why This Matters
🌍 Real World
Validating user input on the server helps prevent errors and security issues in web applications.
💼 Career
Backend developers often write validation logic to ensure data integrity and improve user experience.
Progress0 / 4 steps
1
Set up Express app and JSON parser
Create a variable called express that requires the 'express' module. Then create a variable called app by calling express(). Finally, add the JSON body parser middleware by calling app.use(express.json()).
Express
Hint
Use require('express') to import Express. Then call express() to create the app. Use app.use(express.json()) to parse JSON bodies.
2
Create POST route with validation variables
Add a POST route handler on /submit using app.post. Inside the handler function, create two variables: name and email, which get their values from req.body.name and req.body.email respectively.
Express
Hint
Use app.post('/submit', (req, res) => { ... }) to create the route. Inside, get name and email from req.body.
3
Add validation logic for name and email
Inside the POST handler, add an if statement that checks if name is not a string or is missing, or if email is not a string or does not include '@'. If any check fails, respond with status 400 and JSON { error: 'Invalid input' }.
Express
Hint
Check if name is missing or not a string, or if email is missing, not a string, or missing '@'. Use res.status(400).json(...) to send error.
4
Send success response for valid input
After the validation if block, send a JSON response with status 200 and message { message: 'Data received' }. Then add app.listen(3000) to start the server on port 3000.
Express
Hint
Send success JSON with res.status(200).json({ message: 'Data received' }). Start server with app.listen(3000).
Practice
(1/5)
1. What is the main reason to validate fields in req.body in an Express app?
easy
A. To log user data for analytics
B. To speed up the server response time
C. To change the data format automatically
D. To ensure the data received is complete and correct before processing
Solution
Step 1: Understand the purpose of validation
Validation checks if the data sent by the user is complete and correct.
Step 2: Identify the benefit of validation
It prevents errors and security issues by stopping bad data early.
Final Answer:
To ensure the data received is complete and correct before processing -> Option D
Quick Check:
Validation = Check data correctness [OK]
Hint: Validation means checking data before use [OK]
Common Mistakes:
Thinking validation speeds up server
Assuming validation changes data format
Confusing validation with logging
2. Which middleware is required to parse JSON body data in Express before validating fields?
easy
A. express.json()
B. express.static()
C. express.urlencoded()
D. express.raw()
Solution
Step 1: Identify middleware for JSON parsing
express.json() parses incoming JSON request bodies into JavaScript objects.
B. It uses strict equality instead of loose equality
C. It does not stop execution after sending error response
D. It should use res.json() instead of res.send()
Solution
Step 1: Analyze the error handling flow
The code sends a 400 error but does not return or stop, so it continues to send success response.
Step 2: Identify the fix
Adding 'return' before res.status(400).send(...) stops further execution.
Final Answer:
It does not stop execution after sending error response -> Option C
Quick Check:
Missing return causes double response [OK]
Hint: Return after sending error to stop code [OK]
Common Mistakes:
Ignoring missing return after res.send()
Confusing equality checks with flow control
Thinking res.json() is required for errors
5. You want to validate that req.body.age is a number greater than 18 before processing. Which code snippet correctly validates this and sends a 400 error if invalid?
hard
A. if (!req.body.age || typeof req.body.age !== 'number' || req.body.age <= 18) {
return res.status(400).send('Age must be a number over 18');
}
B. if (req.body.age <= 18) {
res.status(400).send('Age must be over 18');
}
C. if (typeof req.body.age === 'string' && req.body.age > 18) {
return res.status(400).send('Invalid age');
}
D. if (!req.body.age || req.body.age < 18) {
res.send('Age is valid');
}
Solution
Step 1: Check for presence and type of age
Code verifies age exists and is a number using typeof.
Step 2: Check age value is greater than 18
It ensures age is over 18, else sends 400 error with message.
Step 3: Confirm proper use of return to stop execution
Return stops further processing after error response.
Final Answer:
if (!req.body.age || typeof req.body.age !== 'number' || req.body.age <= 18) {
return res.status(400).send('Age must be a number over 18');
} -> Option A