Step-by-Step Guide to Using Express-Validator for Accurate Validation

I am a MERN stack developer and an aspiring AI application engineer. Lets grab a cup of coffee ad chat.
In the constantly changing world of web development, securing user input is essential for building strong applications.
A straightforward example is when you create a backend controller function for user registration or login. The first step in your controller is to validate the data received from the frontend to ensure its accuracy and security.
But wait a second, what do I mean by “validate”? Suppose you are taking the username and password from the user for a login operation. You need to validate that the username is a String (at least) first; otherwise, someone can inject HTML into your page! This is where the benefit of a validator library comes in. Today I will talk about “express-validator”.
So, we are all set up with the motivation. Let us start to see how this can be used in your application. First I will give you a simple example
Installation Guide
Start a project and set your package.json file accordingly. I will go on with ‘module’ so I changed the ‘type’ as module from commonJS. You will need to install express, express-validator and nodemon.
npm i express express-validator
npm install --save-dev nodemon
Create a file named as “index.js”
import express from 'express'
const app = express();
app.use(express.json());
app.get('/hello', (req, res) => {
res.send(`Hello, ${req.query.person}!`);
});
app.listen(3000);
It’s very familiar to you right? If not please revisit this part and come again to this blog. I am not going anywhere.
Now run this file by executing node index.js. The HTTP server should be running, and you can open http://localhost:3000/hello?person=Indranil to salute Indranil! But what if you try to hit http://localhost:3000/hello You will end up having “Hello undefined”.
This is not expected. You don’t want to greet someone when the name is not set!
We will solve this problem using express-validator today.
So we need a validator that will check if a name is present; if not, it will give an error message immediately. We can do further checking on the type of input provided as well, but we will see that later.
For this, we will use Validation Chain, a key concept in express-validator.
Validation Chain
Validation chains are created using functions like body(), params(), query(), headers(), and others.
It's important to note that these validation chains are middleware themselves, and they can be passed to any Express.js route handler. That's exactly what we'll do!
Though a validation chain has three kinds of methods: validators, sanitizers, and modifiers I will talk about mostly validators today.
Here is an example of how to create a validator. I created another file named validator.js. The purpose of this file is to check whether the query parameter called "person" is empty or not. We can also attach an error message using .withMessage(message)
import { query } from "express-validator"
const validator = () => {
return [
query('person')
.notEmpty().withMessage("This field can not be empty")
]
}
export {
validator
}
Similarly, you can perform checks on other requests as well. The format remains the same.
If there is an error i.e no name in the request we will see
{
"errors": [
{
"location": "query",
"msg": "This field can not be empty",
"path": "person",
"type": "field"
}
]
}
// exactly one error which will be passed to the request
// the error is in a field (type: "field");
// this field is called person;
// it's located in the query string (location: "query");
// the error message that was given was "This field can not be empty".
The response from the validator that we have written will be sent with the req to the next step where we will handle the error (if any).
We will use validationResult which is again from express-validator.
import {validationResult} from 'express-validator'
export const validationRes = (req, res, next) => {
const errors = validationResult(req) // On the req we now have all the error data from the previous step
if(errors.isEmpty()){
return next() // if there is no error, proceed to next()
}
const extractedError = []
errors.array().map((err) => extractedError.push(err.msg))
throw new Error(extractedError) // if there is error the error will be thrown
}
Let’s write the last step i.e add our validator and error handling in the route.
import express from 'express'
import { validator } from './validator.js';
import { validationRes } from './validationResult.js';
const app = express();
app.use(express.json());
app.get('/hello', validator(), validationRes, (req, res) => {
res.send(`Hello, ${req.query.person}!`);
});
app.listen(3000);
Take a close look at the routing design where we have added our validator. Whenever a GET request is made, the validator() function will be called. This function will perform the validation, and the result will be attached to the request. The validationRes function will then check for any errors. If there are no errors, it will proceed to the next step. Finally, if everything is okay from the previous step, a callback function will be executed.


To cut the long story short,
In this article, we explore the importance of securing user input in web development and demonstrate how to use the "express-validator" library in a Node.js application. We'll guide you through setting up an Express server, implementing basic validation for query parameters, and handling errors effectively using validation chains and middleware. This step-by-step introduction will help you ensure that your application remains robust and secure.
I hope this helps. This is my first article, so any feedback would be very helpful.



