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.

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay