Using express-validator for data validation in NodeJS

Chau Nguyen
2 min readApr 27, 2023

express-validator is a package that supports data validation and can be used to integrate with the NodeJS express framework to validate API request parameters. In this article, I will guide you on how to use express-validator to validate data sent from the front-end through API calls and output error messages to respond back to the front-end.

Setup and Installation

To begin, you need to set up a NodeJS project using express (using typescript code), which you can learn more about in this article. After setting up your project, the next step is to install express-validator via npm or yarn.

npm install --save express-validator
// or
yarn add express-validator

Creating Validators

Next, you need to create validators for your API requests. Here are two examples: one for login validation and another for validating a user object that meets the data type requirements for creating or updating.

import {body} from 'express-validator'

export const loginValidator = [
body('email', 'Invalid does not Empty').not().isEmpty(),
body('email', 'Invalid email').isEmail(),
body('password', 'The minimum password length is 6 characters').isLength({min: 6}),
]

export const createValidator = [
body('user.username', 'username does not Empty').not().isEmpty(),
body('user.email', 'Invalid email').isEmail(),
body('user.age', 'username must be Alphanumeric').isAlphanumeric(),
body('user.birthday', 'Invalid birthday').isISO8601(), // check date is ISOString
body('user.password', 'password does not Empty').not().isEmpty(),
body('user.password', 'The minimum password length is 6 characters').isLength({min: 6}),
]

How to Use Validators

After defining validators, you can integrate them into the router as shown below:

import {validationResult} from 'express-validator'

router.post('/login', loginValidator, (req, res, next) => {
const errors = validationResult(req)
if (errors.isEmpty()) {
// in case request params meet the validation criteria
return res.status(200).json()
}
res.status(422).json({errors: errors.array()})
});

When there is an error with the API request, the corresponding error message will be responded back to the front-end.

Test result

This article provides a simple guide on using express-validator for data validation. Hopefully, it will help you have a solution to validate data with NodeJS.

For more information about express-validator, please refer to its official documentation. Don’t forget to leave a comment if you have any feedback and like, share, and follow me for future content!

--

--