How to setup an Express request validator

October 14, 2020

Assumptions

  • I am using a MERN stack
  • I have the following npm packages installed:
  "dependencies": {
    "bcryptjs": "^2.4.3",
    "config": "^3.3.2",
    "express": "^4.17.1",
    "express-validator": "^6.6.1",
    "jsonwebtoken": "^8.5.1",
    "mongoose": "^5.10.9"
  },
  "devDependencies": {
    "@babel/cli": "^7.11.6",
    "@babel/core": "^7.11.6",
    "@babel/node": "^7.10.5",
    "@babel/preset-env": "^7.11.5",
    "concurrently": "^5.3.0",
    "nodemon": "^2.0.4"
  }
  • I also setup ES6 type module imports/exports instead of CommonJS require and module.export (e.g.: see details here).

Setup Express middleware to be able to parse a request body

Previously it was a 3rd party npm package (body-parser), now it’s built into express, here is how to enable it in the server.js:

emoji-exclamation Important: it needs to go before we define the routes e.g:

import express from "express"
import Users from "./routes/users.js"
import Auth from "./routes/auth.js"
import Contacts from "./routes/contacts.js"

const app = express()

// initialize middleware (like bodyparser)
// This is a built-in middleware function in Express.
// It parses incoming requests with JSON payloads and is based on body-parser.
// https://expressjs.com/en/api.html#express.json

app.use(express.json())

// define routes

app.use("/api/users", Users)
app.use("/api/auth", Auth)
app.use("/api/contacts", Contacts)

Setup request validation in your route

Here is an example how to validate request values to make sure they:

  • are non-empty
  • are in valid email format
  • have minimum length
import express from "express"
import { check, validationResult } from "express-validator"

const router = express.Router()

export default router.post(
  "/",
  [
    check("name", "name is required").not().isEmpty(),
    check("email", "valid email is required").isEmail(),
    check("password", "pwd is required, 6 or more chars").isLength({ min: 6 }),
  ],
  (req, res) => {
    const errors = validationResult(req)

    errors.isEmpty()
      ? res.send(req.body)
      : res.status(400).json({ errors: errors.array() })
  }
)

In case of validation errors, we send back an HTTP 400 bad request response and the corresponding error messages in json format. For example if we post an empty object as the payload, the response is the following:

Postman express request validation error http 400

Otherwise if we complied with the validation rules we get our json object back as a response.

Hope this helps, cheers! emoji-thumbsup