Validating input in Express using express-validator

By

Learn how to validate input in Express endpoints with express-validator, using body() rules like isEmail() and isLength() to verify data before you trust it.

~~~

Say you have a POST endpoint that accepts the name, email and age parameters:

const express = require('express')
const app = express()

app.use(express.json())

app.post('/form', (req, res) => {
  const name  = req.body.name
  const email = req.body.email
  const age   = req.body.age
})

How do you perform server-side validation on those results to make sure:

The best way to handle validation on any kind of input coming from outside in Express is by using the express-validator package. The code in this post uses express-validator 7, so pin that major when you install it:

npm install express-validator@7

You require body and validationResult from the package. body() checks a field in the request body. There are also query() and param() for query strings and route parameters, and the generic check() that looks in all of them:

const { body, validationResult } = require('express-validator')

We pass an array of body() calls as the second argument of the post() call. Every body() call accepts the parameter name as argument. Then we call validationResult() to verify there were no validation errors. If there are any, we tell them to the client:

app.post('/form', [
  body('name').isLength({ min: 3 }),
  body('email').isEmail(),
  body('age').isNumeric()
], (req, res) => {
  const errors = validationResult(req)
  if (!errors.isEmpty()) {
    return res.status(422).json({ errors: errors.array() })
  }

  const name  = req.body.name
  const email = req.body.email
  const age   = req.body.age
})

Notice I used

There are many more of these methods, all coming from validator.js, including:

You can validate the input against a regular expression using matches().

Dates can be checked using

For exact details on how to use those validators, refer to https://github.com/validatorjs/validator.js#validators.

All those checks can be combined by piping them:

body('name')
  .isAlpha()
  .isLength({ min: 10 })

If there is any error, the server sends a response to communicate the error. For example if the email is not valid, this is what will be returned:

{
  "errors": [{
    "type": "field",
    "value": "not-an-email",
    "msg": "Invalid value",
    "path": "email",
    "location": "body"
  }]
}

The field name is in path. Older versions of express-validator called it param, so if you find code that reads error.param, that is why it’s undefined now.

This default error can be overridden for each check you perform, using withMessage():

body('name')
  .isAlpha()
  .withMessage('Must be only alphabetical chars')
  .isLength({ min: 10 })
  .withMessage('Must be at least 10 chars long')

What if you want to write your own special, custom validator? You can use the custom validator.

In the callback function you can reject the validation either by throwing an exception, or by returning a rejected promise:

app.post('/form', [
  body('name').isLength({ min: 3 }),
  body('email').custom(email => {
    if (alreadyHaveEmail(email)) {
      throw new Error('Email already registered')
    }
  }),
  body('age').isNumeric()
], (req, res) => {
  const name  = req.body.name
  const email = req.body.email
  const age   = req.body.age
})

The custom validator:

body('email').custom(email => {
  if (alreadyHaveEmail(email)) {
    throw new Error('Email already registered')
  }
})

can be rewritten as

body('email').custom(email => {
  if (alreadyHaveEmail(email)) {
    return Promise.reject('Email already registered')
  }
})

Once the input is valid, the next step is to sanitize it.

Want me to talk about your product? You can sponsor this site.

~~~

Related posts about express: