0
0
ExpressHow-ToBeginner · 3 min read

How to Validate Request Body in Express: Simple Guide

To validate the request body in Express, use middleware like express-validator or Joi to define rules and check data before processing. This ensures the data sent by clients is correct and prevents errors or security issues.
📐

Syntax

Validation in Express usually involves middleware functions that check the req.body data. You define validation rules, then run a check before your route handler processes the data.

For example, using express-validator:

  • check() defines validation rules for fields.
  • validationResult() collects errors after validation.
  • If errors exist, respond with error messages; otherwise, continue.
javascript
import express from 'express';
import { check, validationResult } from 'express-validator';

const app = express();
app.use(express.json());

app.post('/user', [
  check('username').isLength({ min: 3 }),
  check('email').isEmail(),
], (req, res) => {
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    return res.status(400).json({ errors: errors.array() });
  }
  res.send('User data is valid');
});
💻

Example

This example shows how to validate a user registration request body with express-validator. It checks that username is at least 3 characters and email is a valid email. If validation fails, it returns a 400 error with details.

javascript
import express from 'express';
import { check, validationResult } from 'express-validator';

const app = express();
app.use(express.json());

app.post('/register', [
  check('username').isLength({ min: 3 }).withMessage('Username must be at least 3 chars'),
  check('email').isEmail().withMessage('Email must be valid'),
], (req, res) => {
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    return res.status(400).json({ errors: errors.array() });
  }
  res.send('Registration data is valid');
});

app.listen(3000, () => console.log('Server running on port 3000'));
Output
POST /register with body {"username":"ab","email":"bademail"} Response: 400 Bad Request { "errors": [ {"msg":"Username must be at least 3 chars","param":"username","location":"body"}, {"msg":"Email must be valid","param":"email","location":"body"} ] } POST /register with body {"username":"abc","email":"abc@example.com"} Response: 200 OK Registration data is valid
⚠️

Common Pitfalls

  • Not using express.json() middleware causes req.body to be undefined.
  • Skipping validationResult() check means errors are ignored.
  • Not returning or ending response after validation errors can cause multiple responses.
  • Using synchronous validation functions incorrectly can block the event loop.
javascript
import express from 'express';
import { check, validationResult } from 'express-validator';

const app = express();
// Missing app.use(express.json()) causes req.body to be undefined

app.post('/wrong', [
  check('name').notEmpty(),
], (req, res) => {
  // Forgot to check validationResult
  res.send('This runs even if data is invalid');
});

// Correct way
app.use(express.json());
app.post('/right', [
  check('name').notEmpty(),
], (req, res) => {
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    return res.status(400).json({ errors: errors.array() });
  }
  res.send('Valid data');
});
📊

Quick Reference

Tips for validating request body in Express:

  • Always use express.json() to parse JSON bodies.
  • Use express-validator or Joi for clear validation rules.
  • Check validationResult(req) to catch errors.
  • Return error responses immediately if validation fails.
  • Keep validation logic separate from business logic for clarity.

Key Takeaways

Use middleware like express-validator to define and run validation rules on req.body.
Always parse JSON bodies with express.json() before validating.
Check validationResult(req) to detect errors and respond early.
Return error responses immediately to avoid running invalid logic.
Clear validation improves API reliability and security.