In this blog post, we will learn how to validate input data in your Express endpoints using the express-validator package. Specifically, we will look at how to validate the name, email, and age parameters in a POST endpoint.

Let’s start by setting up our Express server and configuring it to parse incoming JSON data:

const express = require('express');
const { check, validationResult } = require('express-validator');
const app = express();
app.use(express.json());

Next, let’s define our POST endpoint and perform validation on the input data:

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

In the above example, we are using the check() function from the express-validator package to validate each parameter. We are checking if the name is a string of at least 3 characters, if the email is a valid email address, and if the age is a number.

If any validation errors occur, we use the validationResult() function to get the errors and send them back to the client with a 422 status code.

The express-validator package provides a wide range of validation methods, all coming from validator.js. Some examples include isAlpha(), isNumeric(), isEmail(), isURL(), and many more.

You can also combine multiple validation checks by chaining them together:

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

In addition to the built-in validation methods, you can also create custom validators using the custom() method. Here’s an example of how to use a custom validator to check if an email is already registered:

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

Note that you can reject the validation by either throwing an exception or returning a rejected promise.

By leveraging the express-validator package, you can easily validate input data in your Express endpoints, ensuring that it meets your specific requirements. This improves the overall reliability and security of your application.