Use Express-Validator to clean up the input in Express

You have learned how to validate input from the outside world to your Express application.

When running a public-facing server, you will quickly learn one thing: never trust input.

Even if you sanitize and make sure that people can't use client code to enter weird things, you will still be constrained by people using tools (or even just browser devtools) to POST directly to your endpoint.

Or, the robot will try various ways of use known to humans.

What you need to do is clean up your input.

Thisexpress-validatorpackageYou have been used to verify the input content, and can also be conveniently used to perform cleanup operations.

Assuming you have a POST endpoint that can accept 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 can verify it using the following methods:

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 disinfection by passing the disinfection method in a pipeline after the verification method:

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

Here, I used the following method:

  • trim()Trim characters at the beginning and end of the string (blank by default)
  • escape()replace<,>,&,',"with/And its corresponding HTML entities
  • normalizeEmail()Normalize email addresses. Accept multiple options to lowercase email addresses or subaddresses (e.g.[email protected])

Other disinfection methods:

  • blacklist()Delete characters appearing in the blacklist
  • whitelist()Delete characters that do not appear in the whitelist
  • unescape()Replace the HTML-encoded entities with<,>,&,',"with/
  • ltrim()Similar to trim(), but only trims the characters at the beginning of the string
  • rtrim()Similar to trim(), but only trims the characters at the end of the string
  • stripLow()Remove normally invisible ASCII control characters

Force conversion to format:

  • toBoolean()Convert the input string to a boolean value. Everything except "0", "false" and "" returns true. In strict mode, only '1' and'true' return true
  • toDate()Convert the input string to a date, if the input is not a date, convert it to null
  • toFloat()Convert the input string to a floating point number; if the input is not a floating point number, convert it to NaN
  • toInt()Convert the input string to an integer, if the input is not an integer, convert it to NaN

As with custom validators, you can create custom sanitizers.

In the callback function, you only need to return the cleaned value:

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

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

Download mine for freeExpress.js manual


More crash tutorials: