How to input text validation using express-validator in Nodejs


We can use express-validator in express-Nodejs project to check whether the input satisfy certain criteria provided. To do this first need to install the package

npm i express-validator --save

This will install and add the package as dependency. Use the validator body and validationResult method to validate the input.

Validation rules

This can be achieved using the body inside routes argument as follows

const { body, validationResult } = require('express-validator');
.. for simplicity I ommitted the rest of the code
router.post("/",[

   body('markdown').trim().isLength({min:2})
 
], async (req, res) => {
   
})

The above body check the input named ‘markdown’ and if it contain text smaller than 2 and pull an error. We also performed a trim() operation on the string to avoid spaces.

We can use multiple body block with in the [ ] , for validating other request objects.

Placing the error

An error collection can be grab using the request and validationResult as follows in the route’s arrow function. The method accept the request as parameter and return the error collection.

const { body, validationResult } = require('express-validator');
.. for simplicity I ommitted the rest of the code
router.use(express.json())
router.post("/",[
   body('markdown').trim().isLength({min:2})
], async (req, res) => {
   const errors=validationResult(req)
   if(!errors.isEmpty()){
       return res.status(400).json({errors:errors.array()})
  }
 
})

The errors.array() holding all the errors belonging to the request. When the error catch up, the return statement will fire a response which is showing the errors as JSON string.

Following Express posts may also help you to build better app today

Published by

Manoj

A developer,teacher and a blogger obsessed with Python,Dart and open source world from India

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.