DEV Community

Cover image for Integrate express-validator to your express API
Sunny Praksah
Sunny Praksah

Posted on

Integrate express-validator to your express API

The original post can be found over here.

Why do I need express-validator?

Short and simple if your UI is using forms or multiple input fields and in the backend express application you want to validate those data against database schema, then you need to validate them first before you actually process it. Sure, you can do all the validation manually by writing all sorts of logics and regexes. But why reinvent the wheel if something is doing that for you already. This is where the express-validator library comes in.

I hate too much dependent libraries. what about it?

express-validator is a wrapper around validator.js and uses lodash for its data manipulation, that's it. So basically you have two dependencies. I am sure you must have using lodash already, so no extra packages and libraries to take care of.

Ok genius, but I can write my own middleware to achieve it? how this library of yours better than that?

Man, you are a tough nut to crack. Of course, you can do everything in this world by yourselfff. But think about how easy it will be to validate your express routes. You can do that out of the box by using express-validator in your express application. Ohh and Did I mention you can also sanitize your data? Plus you have all the freedom to customize your error messages. Keep reading and I will show you how.

To explain things I will be taking reference from one of my Github repo https://github.com/sprakash57/Contrivocial.

Prerequisite

  • node.js v6+

Installation

  • npm i -S express-validator

P.S: At the time I am writing this blog, express-validator has version 6.6.1. It may not be the same for you.

Usage

Step 1 - middleware/validation.js (Just to keep every validation at a single place).

Here I am taking an example of user registration with 3 fields namely name, email, & password.

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 })
]
Enter fullscreen mode Exit fullscreen mode

You need to import check first. It takes two parameters. The first one is the field and the second is the error message that you want to send in the response.

You can chain methods on the check to carry out the validations like isEmail or isEmpty. Want some sanitization, you can append sanitization methods as well. A Useful list can be found over here. My favorite is normalizeEmail({ gmail_remove_dots: true }). It will treat sunnyprakash@gmail.com and sunny.prakash@gmail.com as equal.

const { signupValidation } = require('../../middleware/validation');

router.post('/register', signupValidation, userController.register);
Enter fullscreen mode Exit fullscreen mode

The second step is all about tweaking your routes. Inside the user registration route, I have introduced signupValidation middleware that was created in step 1.

Step 3 - controllers/user.js

Now Its time to change our user registration controller a little bit. To catch all the validation messages inside this controller I have imported validationResult from express-validator.

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

exports.register = async (req, res) => {

  const errors = validationResult(req);

  if (!errors.isEmpty()) return res.status(400).json({ errors: errors.array() });

  ......

  ......

}
Enter fullscreen mode Exit fullscreen mode

To get the messages out of the signupValidation method present inside validation.js, you need to pass the request object to it. Once that is done, you can access all error messages in an array format by using errors.array().

And that's all folks, you don't need to touch your app.js. I have just scratched the surface. There is a lot you can achieve. But I think This would be sufficient for a beginner getting started with express. To dig in more you can read their official doc https://express-validator.github.io/docs.

Check out the complete implementation of the above in my Github repo over here. See if it helps to set things up for you. A star to the repo would be highly appreciated.

Top comments (1)

Collapse
 
slidenerd profile image
slidenerd

have you seen tihs post dev.to/nedsoft/a-clean-approach-to...