Example of Node.JS Server-side Validation
routes/api.js import body from express-validator/check and then add middleware in the router to validate as shown below in square brackets
controllers/api.js - add validation result and check if errors variable has any errors to stop action.
routes/api.js import body from express-validator/check and then add middleware in the router to validate as shown below in square brackets
const { body } = require('express-validator/check');
// middleware - Add Product
router.post('/product', [
body('title')
.trim()
.isLength({min: 3}).withMessage('Title too short. Enter a longer title!'),
body('description')
.trim()
.isLength({min: 30, max: 600}).withMessage('Description should be from 30 upto 600 characters!'),
body('price', 'Enter a valid price.')
.isFloat()
.trim(),
], apiController.postProduct);
controllers/api.js - add validation result and check if errors variable has any errors to stop action.
const { validationResult } = require('express-validator/check');
exports.postProduct = (req, res, next) => {
const errors = validationResult(req);
if (errors.isEmpty()) {
const title = req.body.title;
const description = req.body.description;
const price = req.body.price;
// create post in db
res.status(201).json({
message: 'success!',
data: {
id: new Date().toISOString(),
title: title,
description: description,
price: price
}
});
} else {
res.status(422)
.json(
{
message: "Validation failed, entered data is incorrect.",
errors: errors.array()
}
)
}
};
Comments
Post a Comment