Use express-validator to validate input in Express

Learn how to validate any data entered as input in the Express endpoint

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

How to perform server-side verification of these results to ensure:

  • Is the name a string of at least 3 characters?
  • Is the email a real email?
  • Is age a number, between 0 and 110?

The best way to handle validation of any input from outside in Express is to useexpress-validatorpackage:

npm install express-validator

do you needcheckwithvalidationResultObjects in the package:

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

We pass an arraycheck()Call as the second parameterpost()call. Everycheck()call accepts parameter names as parameters. Then we callvalidationResult()Verify that there are no verification errors. If so, we tell customers:

app.post('/form', [
  check('name').isLength({ min: 3 }),
  check('email').isEmail(),
  check('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 })

Note i used

  • isLength()
  • isEmail()
  • isNumeric()

There are many more of these methods, all fromValidator.js, Including:

  • contains(), Check whether the value contains the specified value
  • equals()To check if the value is equal to the specified value
  • isAlpha()
  • isAlphanumeric()
  • isAscii()
  • isBase64()
  • isBoolean()
  • isCurrency()
  • isDecimal()
  • isEmpty()
  • isFQDN(), Is it a fully qualified domain name?
  • isFloat()
  • isHash()
  • isHexColor()
  • isIP()
  • isIn(), Please check if the value is in the array of allowed values
  • isInt()
  • isJSON()
  • isLatLong()
  • isLength()
  • isLowercase()
  • isMobilePhone()
  • isNumeric()
  • isPostalCode()
  • isURL()
  • isUppercase()
  • isWhitelisted(), Check the input against the whitelist of allowed characters

You can use regular expressions to validate the inputmatches().

Can use inspection date

  • isAfter(), Check if the entered date is after the date you passed
  • isBefore()To check if the entered date is before the date you passed
  • isISO8601()
  • isRFC3339()

For exact details on how to use these validators, please seehttps://github.com/chriso/validator.js#validators.

All these checks can be combined in the following ways:

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

If there are any errors, the server will automatically send a response to convey the error. For example, if the email is invalid, the following will be returned:

{
  "errors": [{
    "location": "body",
    "msg": "Invalid value",
    "param": "email"
  }]
}

You can use the following command to override this default error for each inspection:withMessage():

check('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 itcustomValidator.

In the callback function, you can reject verification by raising an exception or returning a rejected promise:

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

Custom validator:

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

Can be rewritten as

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

Download mine for freeExpress.js manual


More crash tutorials: