10th Feb 2022

Node.js Form Data Validation Using express-validator

Build React Application

Introduction

When developing apps, especially client-facing applications, server-side validation is essential. This is because mortal input alone can not be trusted, as it sometimes contains false or dangerous information. The maturity of the input can be sorted out using customer- side confirmation, but garçon- side confirmation is still necessary. There are other styles for validating data inNode.js, but in this tutorial, we'll concentrate on express- validator. Express-validator is a library that encases validator.js and makes its features available as a collection of middlewares.

Establishing The Project

In this article, we'll develop a prototype user registration and login backend server using Node.js. With the use of these fields, we'll impose specific guidelines and validate all data that comes in.

We'll create a project folder, enter it, then initialise it to get things going:

                            
                                
  mkdir  NodeWithBodyValidator
  cd  NodeWithBodyValidator
  npm  init -y
  
                            
                        

Form data validation is a crucial step in any web application. It ensures that the data entered by the user is valid and meets certain requirements before it is processed by the server. In this tutorial, we will explore how to use the express-validator library to validate form data in a Node.js application using the Express.js framework. First, we need to install the express-validator library by running the following command in the terminal:

                                
                                    
  npm  i  express-validator
  
                                
                            

Next, we need to import the library in our application and set it up as middleware:.

We'll be utilising the Node.js framework "express," which is designed for small web apps. This will be used by our backend server to manage routing.
Then, 'body-parser' which is a middleware that will assist us in parsing user input from incoming requests into the req.body object.
And, 'express-validator' the library we'll be utilising to manage incoming input validation .

Now Produce a train index.js in the root directory of the design and bury the below code. In the below section we will get to the confirmation part(bodyValidators, requestValidators).

                                
                                    
  var express = require("express");
  const bodyValidators = require('./dto-validators');
  const requestValidators = require('./request-validator');
  var app = express();
  app.use(express.json());
  
  app.get('/get',(req,res)=>{
      res.send("Hello world");
  });
  
  app.post('/Register', bodyValidators.registerValidator, requestValidators.validateRequest, (req,res)=>{
      res.json({
          Email:req.body.Email,
          Password:req.body.Password,
          Active:req.body.Active
      });
  });
  
  app.listen(6000,()=>{
      console.log('server is running at the port 6000');
  })
                                
                            

Express-validator and Standard Validation Rules

We will learn how to add basic validation and sanitization rules to incoming requests in this section. First, we want to determine whether the value entered into the email is a legitimate email address, 'Password' has at least 6 characters and an 'Active' field which requires boolean to be sent.

We can directly to include the express-validator middleware to our API which is done here, instead we will organize our project in a better way which will be helpful if our application is big(for code reusability).

We will define our validation rules in a file named dto-validators.js , create the file in the root directory of the project, copy paste the below code in it.

                                
                                    
  const validation = require('express-validator');
  const registerValidator = [
      validation.body('Email').isEmail(),
      validation.body('Password').isLength({ min: 5 }),
      validation.body('Active').isBoolean()
  ];
  
  module.exports = {
      registerValidator
  }
                                
                            

We have created a variable named registerValidator which has the validations defined in it.
1. 'Email' field in the request body is a valid email address
2. 'Password' field in the request body has a minimum length of 5 characters
3. 'Active' field in the request body is a boolean value
Later we can also define other validations if required.

The middleware must then be connected to our API so that relevant notifications are sent in the event of a validation error. To do that let’s create a new file named request-validator.js and paste the below code in it.

                                
                                    
  const validation = require('express-validator');
  const validateRequest = function (req, res, next) {
      const errors = validation.validationResult(req);
      if (!errors.isEmpty()) {
          return res.status(400).json({ errors: errors.array() });
      }
      next();
  }
  
  module.exports = {
      validateRequest
  }
                                
                            

Now our application is now set up with the validators, let's run it by using the command

                                
                                    
  node index.js
  
                                
                            

When making the API call, if any validation errors are found, the validateRequest middleware will shoot a response with a 400 status law and the array oferrors.However, the request will be reused by the route tutor, If no crimes are set up.

Let's make a valid request using postman

Let's make a request using postman, with an username null An error or failure response will be displayed.

Conclusion

In summary, the express-validator library provides an easy way to validate form data in a Node.js application using the Express.js framework. By defining validation rules as middleware functions, we can easily reuse them in multiple route handlers, ensuring that the data entered by the user is valid before it is processed by the server.

About Us

  • VS Online Services : Custom Software Development

VS Online Services has been providing custom software development for clients across the globe for many years – especially custom ERP, custom CRM, Innovative Real Estate Solution, Trading Solution, Integration Projects, Business Analytics and our own hyperlocal e-commerce platform vBuy.in and vsEcom.

We have worked with multiple customers to offer customized solutions for both technical and no technical companies. We work closely with the stake holders and provide the best possible result with 100% successful completion To learn more about VS Online Services Custom Software Development Solutions or our product vsEcom please visit our SaaS page, Web App Page, Mobile App Page to know about the solution provided. Have an idea or requirement for digital transformation? please write to us at siva@vsonlineservices.com

Let's develop your ideas into reality