DEV Community

Jad Khoury
Jad Khoury

Posted on

Simple Way to Validate Payload with Express JS

Introduction:

The purpose of this tutorial is to provide an easy and concise way to validate payload with an Express JS application.

We will be using the simple-body-validator library to achieve our goal of validating payloads

Let's say that we would like to validate the following payload.

{
   "name":"John",
   "email":"John@gmail.com",
   "age":28
}
Enter fullscreen mode Exit fullscreen mode

Installation:

To get started, install the simple-body-validator library:

npm i simple-body-validator
Enter fullscreen mode Exit fullscreen mode

Validation Rules:

The simple-body-validator library offers a variety of validation rules. You can find the full list of rules in the documentation here.

const rules = {
   name: 'required|string|min:3',
   email: 'required|email',
   age: 'min:18'
};
Enter fullscreen mode Exit fullscreen mode

Code Example:

const express = require('express');
const bodyParser = require('body-parser');
const {make} = require('simple-body-validator');

const app = express();
const port = 3000;

// parse application/json
app.use(bodyParser.json());

const rules = {
   name: 'required|string|min:3',
   email: 'required|email',
   age: 'min:18',
};

app.post('/user', (req, res) => {
      const validator = make(req.body, rules);

      if (!validator.validate()) {
         res.status(422).json(validator.errors().all(false));
         return;
      }

      res.send('SUCCESS');
});

app.listen(port, () => {
  console.log(`Example app listening on port ${port}`)
});

Enter fullscreen mode Exit fullscreen mode

With this setup, your validation is complete! We recommend that you go through the documentation for more complex use cases.

Top comments (0)