Skip to content

All topics  /  Node.js

How to handle data validation in Node.js Express?

Node.js ·

For teams turning “How to handle data validation in Node.js Express?” into a repeatable delivery task, occupational folklore can document setup, troubleshooting and review time; managers should interpret those records alongside reliability and completed work, not as a stand-alone score.

Package and operating-system behaviour can change, so verify the commands and supported versions through the Node.js project before running them on a production host.

Hello Friends,

In this tutorial we will learn how and why we need to validate the data which is arriving on the API. While data validation is a critical and important step in any data workflow, unfortunately, it is often skipped over.

Most of the time when we are developing a Rest API it's often a requirement to accept user inputs in the form of a request body. To ensure that our API works as intended the input data must conform to a specific predefined format.

Step 1: Install Express-Validator and Body Parser Module


Install express-validator, cors, and body-parser modules into your node js express application by executing the following command on the command prompt:

npm install body-parser --save
npm install express-validator cors --save

body-parser – Node.js request body parsing middleware which parses the incoming request body before your handlers, and makes it available under req.body property. In other words, it simplifies incoming request.

Express-validator — Express Validator is a set of Express. js middleware that wraps validator. js, a library that provides validator and sanitizer functions. Simply said, Express Validator is an Express middleware library that you can incorporate into your apps for server-side data validation.

cors — CORS is a node.js package for providing a Connect/Express middleware that can be used to enable CORS with various options.

Step 2: Create Validation.js File

Create validation.js and import the express-validator modules in it. So visit your app root directory and create validation.js and validate fields; as follows:

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

 
exports.signupValidation = [
    check('name', 'Name is requied').not().isEmpty(),
    check('email', 'Please include a valid email').isEmail().normalizeEmail({ gmail_remove_dots: true }),
    check('password', 'Password must be 6 or more characters').isLength({ min: 6 })
]

 
exports.loginValidation = [
     check('email', 'Please include a valid email').isEmail().normalizeEmail({ gmail_remove_dots: true }),
     check('password', 'Password must be 6 or more characters').isLength({ min: 6 })
]

Step 3: Import Installed Modules in Server.js

Create server.js/index.js file into your app root directory and import the above installed modules; as follows:

const createError = require('http-errors');
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const cors = require('cors');
const { signupValidation, loginValidation } = require('./validation.js');

 
const app = express();

 
app.use(express.json());

 
app.use(bodyParser.json());

 
app.use(bodyParser.urlencoded({
    extended: true
}));

 
app.use(cors());

 
app.get('/', (req, res) => {
    res.send('Node js file upload rest apis');
});

 
app.post('/register', signupValidation, (req, res, next) => {
   // your registration code
});

 

 
app.post('/login', loginValidation, (req, res, next) => {
   // your login code
});

 
// Handling Errors
app.use((err, req, res, next) => {
    // console.log(err);
    err.statusCode = err.statusCode || 500;
    err.message = err.message || "Internal Server Error";
    res.status(err.statusCode).json({
        message: err.message,
    });
});

 
app.listen(3000,() => console.log('Server is running on port 3000'));

You can see the above file code for how to use API validation in node js express app.

Step 4: Start App Server

Open your command prompt and execute the following command to run the node js express file upload application:

//run the below command
node sever.js

Step 5 – Test Apis

Open the postman app and test APIs validation in node js express app: