Node js validation rest API example; In this tutorial, you will learn how to validate rest API data on node js express app using express-validator module.
A validation library for node.js. NIV (Node Input Validator) is a validation library for node. js. You can also extend library to add custom rules. Note: For use case of any rule, please check test cases, If you have any doubt or confusion with documentation or rule behaviour.
Node js Express REST APIs Validation Tutorial
- Step 1 – Install Express-Validator and Body Parser Module
- Step 2 – Create Validation.js File
- Step 3 – Import Installed Modules in Server.js
- Step 4 – Start App Server
- Step 5 – Test Apis
Step 1 – Install Express-Validator and Body Parser Module
Install express-validator, cors and body-parser modules into your node js express application by executing the following command on command prompt:
npm install body-parser --save npm install express-validator cors --save
- body-parser – Node.js request body parsing middleware which parses the incoming request body before your handlers, and make it available under req.body property. In other words, it simplifies the incoming request.
- Express-validator — Express Validator is a set of Express. js middleware that wraps validator. js , a library that provides validator and sanitizer functions. Simply said, Express Validator is an Express middleware library that you can incorporate in your apps for server-side data validation.
- cors — CORS is a node.js package for providing a Connect/Express middleware that can be used to enable CORS with various options.
Step 2 – Create Validation.js File
Create validation.js and import the express-validator modules in it. So visit your app root directory and create validation.js and validate fields; as following:
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 })
]
exports.loginValidation = [
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 })
]
Step 3 – Import Installed Modules in Server.js
Create server.js/index.js file into your app root directory and import above installed modules; as following:
const createError = require('http-errors');
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const cors = require('cors');
const { signupValidation, loginValidation } = require('./validation.js');
const app = express();
app.use(express.json());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(cors());
app.get('/', (req, res) => {
res.send('Node js file upload rest apis');
});
app.post('/register', signupValidation, (req, res, next) => {
// your registration code
});
app.post('/login', loginValidation, (req, res, next) => {
// your login code
});
// Handling Errors
app.use((err, req, res, next) => {
// console.log(err);
err.statusCode = err.statusCode || 500;
err.message = err.message || "Internal Server Error";
res.status(err.statusCode).json({
message: err.message,
});
});
app.listen(3000,() => console.log('Server is running on port 3000'));
You can see the above file code for how to use API validation in node js express app.
Step 4 – Start App Server
Open your command prompt and execute the following command to run node js express file upload application:
//run the below command node sever.js
Step 5 – Test Apis
Open postman app and test apis validation in node js express app:
Conclusion
Node js validation rest API example; In this tutorial, you have learned how to validate rest API data on node js express app using express-validator module.
I’m glad that you provide information about Validation in Node js Express Rest API that was very helpful for me. Thank you for providing such a nice article. Expect more articles in the future.