0
0
Expressframework~5 mins

Validation error response formatting in Express

Choose your learning style9 modes available
Introduction

We format validation error responses to clearly tell users what went wrong with their input. This helps users fix mistakes easily.

When a user submits a form with missing or wrong data.
When an API receives invalid input parameters.
When you want to give clear feedback on what fields need correction.
When you want to keep your API responses consistent and easy to understand.
Syntax
Express
res.status(400).json({
  errors: [
    { field: 'fieldName', message: 'Error message' }
  ]
});
Use HTTP status code 400 for bad requests caused by validation errors.
Return an array of error objects so users can see all problems at once.
Examples
This example shows a single validation error for a missing email field.
Express
res.status(400).json({
  errors: [
    { field: 'email', message: 'Email is required' }
  ]
});
This example shows multiple validation errors returned together.
Express
res.status(400).json({
  errors: [
    { field: 'password', message: 'Password must be at least 8 characters' },
    { field: 'username', message: 'Username cannot contain spaces' }
  ]
});
Sample Program

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.

Express
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'));
OutputSuccess
Important Notes

Always use clear and simple messages so users understand what to fix.

Keep the error response structure consistent across your API.

Summary

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.