I'm using multer to upload documents.
So i i have 3 fields for users to upload the files .
I'm also using express-validator to validate the fields(wether they are empty or not).
Upload = multer({
storage: fileStorage,
limits: {
fileSize: 5 * 1024 * 1024
},
fileFilter: function (req, file, callback) {
var ext = path.extname(file.originalname);
if (ext !== '.png' && ext !== '.jpg' && ext !== '.jpeg' && ext !== ".pdf") {
return callback(new Error('PDF OR images allowed only'))
}
callback(null, true)
},
}).fields([
{
name: 'passport', maxCount: 1
},
{
name: 'Certificate', maxCount: 1
},
{
name: 'personalPhoto', maxCount: 1
}
])
when leaving an empty field the express-validator check() throws an error which is great. but multer keeps uploading the rest of the files.
that's how I'm handling the check() after the upload.
await check('personalPhoto').custom((value, { req }) => {
if (!req.files['personalPhoto']) throw new Error("it is required");
return true;
}).run(req)
I tried checking if the req.files[file] exist in the fileFilter and throw the error on the callback but the check() keeps throwing error for the 3 files when i check for 1 file only !!
if(req.files['personalPhoto'] === undefined){
return callback(new Error('no'))
}
is there anyway to handle this issue? since you can't use the check() before multer?