Getting Started
One of the best ways to learn is by seeing examples! So let’s dive in and start coding.
Set up
You can integrate the validate-express-req-body in to any of the express.js project with a simple steps. Our package is support CJS, ESM and TypeScripts so this is the basic examples:
- Common JS
- ES Modules
index.js
const express = require("express");
const validateRequestBody = require("validate-express-req-body");
const createUserRules = require("../rules/create-user.rules");
const app = express();
app.use(express.json());
app.post("/create-user", validateRequestBody(createUserRules), (req, res) => {
res.send(`Request is valid!, req.body: ${req.body}`);
});
app.listen(3000, () => {
console.log("Server is running on port 3000");
});
rules/create-user.rules.js
module.exports = [
{
key: "email",
type: "email",
required: true,
},
{
key: "first_name",
type: "string",
required: true,
min: 5,
max: 15,
},
{
key: "last_name",
type: "string",
required: false,
min: 5,
max: 15,
},
{
key: "roles",
type: "array",
required: true,
min: 1,
},
];
index.js
import express from "express";
import validateRequestBody from "validate-express-req-body";
import createUserRules from "./rules/create-user.rules.js";
const app = express();
app.use(express.json());
app.post("/create-user", validateRequestBody(createUserRules), (req, res) => {
res.send(`Request is valid!, req.body: ${req.body}`);
});
app.listen(3000, () => {
console.log("Server is running on port 3000");
});
rules/create-user.rules.js
const createUserRules = [
{
key: "email",
type: "email",
required: true,
},
{
key: "first_name",
type: "string",
required: true,
min: 5,
max: 15,
},
{
key: "last_name",
type: "string",
required: false,
min: 5,
max: 15,
},
{
key: "roles",
type: "array",
required: true,
min: 1,
},
];
export default createUserRules;
The middleware we’ve set up will check the request body against the rules you’ve given. If the request body follows all the rules, it will return the validated request body for further use.
Error
If the request body fails validation, the middleware responds with a status of 200 OK
and an object containing the following:
{
"status": 400,
"message": ["first_name is required", "roles type is array, it should be at least 1 items"]
}