Validation and Sanitization

Sometimes, receiving input in a HTTP request isn’t only about making sure that the data is in the right format, but also that it is free of noise.
So here we will get to know some sanitizers that can be used to take care of the data that comes in.

The express-validator package is use to validate input can also conveniently used to perform sanitization.

Let’s begin

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
})

You might validate it using:

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

app.use(express.json())

app.post('/form', [
  check('name').isLength({ min: 3 }),
  check('email').isEmail(),
  check('age').isNumeric()
], (req, res) => {
  const name  = req.body.name
  const email = req.body.email
  const age   = req.body.age
})

You can add sanitization by piping the sanitization methods after the validation ones:

app.post('/form', [
  check('name').isLength({ min: 3 }).trim().escape(),
  check('email').isEmail().normalizeEmail(),
  check('age').isNumeric().trim().escape()
], (req, res) => {
  //...
})

Here are the methods used above:

Other sanitization methods:

Force conversion to a format:

In the callback function you just return the sanitized value:

const sanitizeValue = value => {
  //sanitize...
}

app.post('/form', [
  check('value').customSanitizer(value => {
    return sanitizeValue(value)
  }),
], (req, res) => {
  const value  = req.body.value
})