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
- 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
- Create REST-API using sequelize -MariaDB ORM in Nodejs - How to create REST-API using sequelize ORM for MariaDB in Node-Expressjs
- How to interact with input in Reactjs - How to handle state and event of input element in React apps
- Create REST-API using sequelize-Mysql in Nodejs - How to create REST-API using sequelize-MySQL ORM in Node-Expressjs