A snippet of my code where i show my defined router,checking body param and checking for validation error.
My defined Post request:
router.post("/addEmployee",upload.any(), function(req, res, next) {
/*I used multer because body data from multipart/form-data*/
var input = JSON.parse(req.body.data);
Server validation: // validation not work because req.checkBody only get bodyData now i am using multipart/form-data (req.body.data)
req.checkBody('EMPID', "**EMPID must be Integer**").notEmpty().isNumeric();
req.checkBody('PAYROLLID', "**PAYROLLID must be Integer**").notEmpty().isNumeric();
.....
....
Check validation error
var validationError = req.validationErrors(); //check error
// if (validationError) { //suppose get error -- throw that error
res.json(validationError[0].msg);
} else { //validation success
......strong text
Validation in node. js can be easily done by using the express-validator module. This module is popular for data validation. There are other modules available in market like hapi/joi, etc but express-validator is widely used and popular among them.
validationResult(req)Extracts the validation errors from a request and makes them available in a Result object. Each error returned by . array() and . mapped() methods has the following format by default: { "msg": "The error message", "param": "param.
js file inside the helper folder as seen below: const Validator = require('validatorjs'); const validator = async (body, rules, customMessages, callback) => { const validation = new Validator(body, rules, customMessages); validation. passes(() => callback(null, true)); validation. fails(() => callback(validation.
Joi can be used for creating schemas (just like we use mongoose for creating NoSQL schemas) and you can use it with plain Javascript objects. It's like a plug n play library and is easy to use. On the other hand, express-validator uses validator. js to validate expressjs routes, and it's mainly built for express.
Use express validator middleware after the multer that's why express validator work naturally
This example work for me , try this
import require dependencies
var fs = require('fs');
var path = require('path');
var multer = require('multer');
var mkdirp = require('mkdirp');
configure multer
var obj = {};
var diskStorage = multer.diskStorage({
destination:function(req,file,cb){
var dest = path.join(__dirname,'/uploads');
mkdirp(dest,function(err){
if(err) cb(err,dest);
else cb(null,dest);
});
},
filename:function(req,file,cb){
var ext = path.extname(file.originalname);
var file_name = Date.now()+ext;
obj.file_name = file_name;
cb(null,file_name);
}
});
var upload = multer({storage:diskStorage});
prepare validation middleware
var validator = function(req,res,next){
req.checkBody('name').notEmpty().withMessage('Name field is required');
req.checkBody('email')
.notEmpty()
.withMessage('Email field is required')
.isEmail()
.withMessage('Enter a valid email address')
.isEmailExists()
.withMessage('Email address already exists');
req.checkBody('password').notEmpty().withMessage('Password field is required');
req.checkBody('retype_password').notEmpty().withMessage('Retyp password field is required');
req.checkBody('password').isEqual(req.body.retype_password).withMessage('Password and confirm password did not match.');
req.checkBody('address').notEmpty().withMessage('Address field is required');
req.asyncValidationErrors().then(function() {
next();
}).catch(function(errors) {
req.flash('errors',errors);
res.status(500).redirect('back');
});
}
save requested data into db
router.post('/store',upload.single('avatar'),validator,async function(req,res,next){
var newUser = User({
name:req.body.name,
email:req.body.email,
password:req.body.password,
avatar:obj.file_name,
address:req.body.address,
created_at:new Date()
});
try{
await newUser.save();
req.flash('success_message','New user has been successfully created');
return res.redirect('back');
}catch(err){
throw new Error(err);
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With