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
- Create a docker image of Node-Express API – Part II - How to build Node-Express project Docker Image using Node base image
- How to clear all element in mongoose object array in Nodejs - How to clear elements in a mongodb object array
- Use dotenv to store configurations in Reactjs - use dotenv in Reactjs to store API base URL
- How to export multiple components in Reactjs - How to render export multiple components in React
- How to create ant row design for Reactjs - Quickly create a row design using Ant Design customize UI for React component
- Ant layout for Reactjs apps - How to create a app layout with Ant Design UI Kit in Reactjs
- How to render child components in Reactjs - How to render child components in React
- How to add element to mongoose object array in Nodejs - How to add element to a mongodb object array
- How to auto create tables based on sequelize models - Auto create table based on sequelize models
- How to resolve sequelize-JSON.parse error in Node - How to resolve JSON.Parse error in sequelize