Introduction
We format validation error responses to clearly tell users what went wrong with their input. This helps users fix mistakes easily.
Jump into concepts and practice - no test required
We format validation error responses to clearly tell users what went wrong with their input. This helps users fix mistakes easily.
res.status(400).json({ errors: [ { field: 'fieldName', message: 'Error message' } ] });
res.status(400).json({ errors: [ { field: 'email', message: 'Email is required' } ] });
res.status(400).json({ errors: [ { field: 'password', message: 'Password must be at least 8 characters' }, { field: 'username', message: 'Username cannot contain spaces' } ] });
This Express server has a POST /register route. It checks if email and password are valid. If not, it sends back a 400 status with a list of errors. If all is good, it sends a success message.
import express from 'express'; const app = express(); app.use(express.json()); app.post('/register', (req, res) => { const { email, password } = req.body; const errors = []; if (!email) { errors.push({ field: 'email', message: 'Email is required' }); } if (!password || password.length < 8) { errors.push({ field: 'password', message: 'Password must be at least 8 characters' }); } if (errors.length > 0) { return res.status(400).json({ errors }); } res.status(200).json({ message: 'Registration successful' }); }); app.listen(3000, () => console.log('Server running on port 3000'));
Always use clear and simple messages so users understand what to fix.
Keep the error response structure consistent across your API.
Validation error responses help users fix input mistakes.
Use HTTP 400 status and return an array of error objects.
Clear messages and consistent format improve user experience.
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');
});if (!req.body.name) {
res.json({ errors: [{ msg: 'Name is required' }] });
res.status(400);
}const errors = [
{ field: 'email', message: 'Invalid email' },
{ field: 'password', message: 'Password too short' }
];
// What is the correct response code?