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
Validation error response formatting
📖 Scenario: You are building a simple Express server that accepts user data. You want to send clear error messages back to the client when the data is invalid.
🎯 Goal: Create an Express route that validates incoming JSON data and sends a formatted error response if validation fails.
📋 What You'll Learn
Create an Express app with a POST route at /submit
Check if the request body has a username field
If username is missing, respond with status 400 and a JSON error message
Format the error response as { error: 'Username is required' }
If username exists, respond with status 200 and { message: 'Success' }
💡 Why This Matters
🌍 Real World
APIs often need to validate user input and send clear error messages so clients know what went wrong.
💼 Career
Backend developers frequently write validation logic and format error responses to improve API usability and reliability.
Progress0 / 4 steps
1
Set up Express app and JSON parsing
Create an Express app by requiring express and calling express(). Use app.use(express.json()) to parse JSON bodies.
Express
Hint
Remember to import Express and enable JSON body parsing.
2
Create POST route at /submit
Add a POST route handler for /submit using app.post('/submit', (req, res) => { }).
Express
Hint
Use app.post to create the route.
3
Check for username and send error response
Inside the /submit route, check if req.body.username is missing. If missing, respond with res.status(400).json({ error: 'Username is required' }).
Express
Hint
Use an if statement to check req.body.username.
4
Send success response if username exists
If username exists, respond with res.status(200).json({ message: 'Success' }) inside the /submit route.
Express
Hint
Send a success JSON response with status 200.
Practice
(1/5)
1. What HTTP status code is typically used to indicate validation errors in an Express API response?
easy
A. 400 Bad Request
B. 200 OK
C. 500 Internal Server Error
D. 404 Not Found
Solution
Step 1: Understand HTTP status codes for client errors
Validation errors occur when the client sends bad data, so a 4xx code is appropriate.
Step 2: Identify the specific code for bad input
400 Bad Request is the standard code for invalid input from the client.
Final Answer:
400 Bad Request -> Option A
Quick Check:
Validation errors use 400 status [OK]
Hint: Validation errors always use 400 status code [OK]
Common Mistakes:
Using 200 OK for validation errors
Confusing 500 Internal Server Error with validation errors
Using 404 Not Found for input mistakes
2. Which of the following is the correct way to send a JSON validation error response in Express?
easy
A. res.status(400).send('Validation failed')
B. res.json({ error: 'Validation error' })
C. res.status(400).json({ errors: [{ msg: 'Invalid input' }] })
D. res.sendStatus(200)
Solution
Step 1: Use status 400 for validation errors
The response must have status 400 to indicate a client error.
Step 2: Format the response as JSON with an errors array
Returning an object with an errors array containing message objects is the standard pattern.
Hint: Use res.status(400).json({ errors: [...] }) for validation errors [OK]
Common Mistakes:
Sending plain text instead of JSON
Omitting the status code
Using 200 status for errors
3. Given this Express route snippet, what will be the JSON response if the input validation fails?
app.post('/user', (req, res) => {
const errors = [];
if (!req.body.email) errors.push({ msg: 'Email is required' });
if (errors.length > 0) {
return res.status(400).json({ errors });
}
res.send('User created');
});
medium
A. {"error":"Email missing"} with status 400
B. {"errors":[{"msg":"Email is required"}]} with status 400
C. "User created" with status 200
D. Empty response with status 400
Solution
Step 1: Check validation logic for missing email
If email is missing, an error object with msg 'Email is required' is added to errors array.
Step 2: Return JSON with errors array and status 400
Since errors array is not empty, the response sends status 400 and JSON containing errors array.
Final Answer:
{"errors":[{"msg":"Email is required"}]} with status 400 -> Option B
Quick Check:
Validation fails -> 400 + errors array JSON [OK]
Hint: Errors array with messages sent with 400 status [OK]
Common Mistakes:
Returning success message despite errors
Wrong JSON key like 'error' instead of 'errors'
Not setting status 400
4. Identify the bug in this Express validation error response code:
if (!req.body.name) {
res.json({ errors: [{ msg: 'Name is required' }] });
res.status(400);
}
medium
A. Status code must be set before sending response
B. Response should use res.send instead of res.json
C. Errors array should be a string, not an object
D. No bug, code is correct
Solution
Step 1: Check order of status and response methods
res.status(400) must be called before sending the response to set status properly.
Step 2: Identify that res.json sends response immediately
Calling res.json first sends the response with default status 200, so status(400) after has no effect.
Final Answer:
Status code must be set before sending response -> Option A
Quick Check:
Set status before res.json/send [OK]
Hint: Call res.status before res.json/send [OK]
Common Mistakes:
Setting status after sending response
Using res.send instead of res.json (not a bug but less clear)
Not sending any status code
5. You want to send multiple validation errors in a consistent format in Express. Which code snippet correctly formats and sends these errors with HTTP 400 status?
const errors = [
{ field: 'email', message: 'Invalid email' },
{ field: 'password', message: 'Password too short' }
];
// What is the correct response code?
hard
A. res.status(400).json({ errorMessages: errors })