How to use the express-validator package

The express-validator package is an npm package that makes it much easier to validate input fields (for user authentication).

First, at the top of our server file, we need to get access to the check and validationResult methods from express-validator:

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

Then, when you are handling the post route of a form, you can implement validation. First, you add a new parameter to the post method; it should be an empty JS array:

app.post('/', [], (req, res) => {
});

Within the array, run the check function on each field and give it the requirements you want to check for. For example, you can check if the input is an email or has a minimum length:

app.post('/', [
   // username must be an email
   check('username').isEmail(),
   // password must be at least 5 chars long
   check('password').isLength({ min: 5 })
], (req, res) => {
});

Then, in the callback, you create a variable called errors to hold any errors from the validation checks in the above array:

app.post('/', [
   check('username').isEmail(),
   check('password').isLength({ min: 5 })
], (req, res) => {
   // Finds the validation errors in this request and puts them in an array called errors
   const errors = validationResult(req);
});

Then, we check if the errors object holds an errors. If so, we can do stuff with the errors. If not, we can do stuff with the inputs:

app.post('/', [
   check('username').isEmail(),
   check('password').isLength({ min: 5 })
], (req, res) => {
   const errors = validationResult(req);

   if (!errors.isEmpty()) {
      return res.status(400).json({ errors: errors.array() });
   }

   User.create({
      username: req.body.username,
      password: req.body.password
   }).then(user => res.json(user));
});

In the event of an error, we send a 400 Bad Request using res.status(400). This simply means that things didn’t go as planned. Then, we get an array of error messages that correspond with the input validations that failed. The json response object will look something like this:

{
   "errors": [
      {
         "location": "body",
         "params": "username",
         "msg": "Insert custom or default error message here",
      }, 
      {
         "location": "body",
         "params": "password",
         "msg": "Please enter a correct password",
      }
   ]
}

More on the check function

We can pass a second optional parameter into the check function which will serve as a custom error message. If we don’t pass this parameter, it will give some generic error message.

check('name', 'Name is required')

Check if a field is empty

check('name', 'Name is required').not().isEmpty()

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s