Introduction

It is imperative to carry out server-side validation when building applications - especially client-facing applications. The reason being, one can never rely on the user’s input alone; as these inputs sometimes contain bogus/malicious data.

Client-side validation is a great way to sift through most of the input, but you still need to perform server-side validation as well.

There are many ways to validate data in Node.js and in this article, we will be taking a look at  express-validator. Express-validator is a library which wraps around validator.js and exposes its functions as a set of middlewares.

Project Setup

For this tutorial, we will be building a demo backend server to mock user registration and login with Node.js. These fields will enforce certain rules and we’ll validate the data that comes through.

Please note we will not be handling actual user registration and login logic i.e saving user data and implementing authentication as this is outside the scope of this article.

To get started, we will create a project folder, navigate into it and initialize it:

## Create the project folder
$ mkdir express-validator-tut

## Navigate into the project folder
$ cd express-validator-tut

## Initialize project
$ yarn init -y
## OR
$ npm init -y

When done, we will install the following dependencies by running the command below:

$ yarn add body-parser express express-validator
## OR
$ npm i body-parser express express-validator

#javascript #node #validation

Form Data Validation in Node.js with express-validator
2.85 GEEK