0

I am trying to validate a form that contains an image using multer and other fields using express-validator , but in the post route always get an undefined error (req.validationError) , any solution ?

server.js

const express = require('express');
const { check, validationResult  , body} = require('express-validator');
var mkdirp = require('mkdirp');
var fs = require('fs-extra');
const path = require('path');
const multer = require('multer');
const cors = require('cors');
const morgan = require('morgan');
var rezizeimg = require('resize-img');
var adminrouter = express.Router();

adminrouter.post('/add_products',[check('description','description should not be empty ').notEmpty(),
        check('title','title should not be empy').notEmpty(),
        check('price','price should not be empty ').isDecimal()



],  (req,res)=> {
    let upload = multer({storage: storage, fileFilter: helpers.imageFilter}).single('profile_pic');

    upload(req, res, function (err) {
        // req.file contains information of uploaded file
        // req.body contains information of text fields, if there were any

        if (req.fileValidationError) {
            console.log(req.fileValidationError);
            return res.send(req.fileValidationError);
        } else if (!req.file) {
            filerror = 'Please select an image to upload';
        } else if (err instanceof multer.MulterError) {
            console.log(err);
            filerror = err;


        } else if (err) {
            console.log(err);
            return res.send(err);

        }



helpers.js

const imageFilter = function(req, file, cb) {
    // Accept images only
    if (!file.originalname.match(/\.(jpg|JPG|jpeg|JPEG|png|PNG|gif|GIF)$/)) {
        req.fileValidationError = 'Only image files are allowed!';
        return cb(new Error('Only image files are allowed!'), false);
    }
    cb(null, true);
};
exports.imageFilter = imageFilter;
Jay
  • 19
  • 2
itjuba
  • 518
  • 4
  • 23
  • Visit https://stackoverflow.com/questions/63632356/multer-and-express-validator-creating-problem-in-validation for the best response to your issue – Daniel OUATTARA Dec 06 '22 at 00:15
  • [issue description & solution here](https://stackoverflow.com/questions/63632356/multer-and-express-validator-creating-problem-in-validation) – Daniel OUATTARA Dec 06 '22 at 00:17

1 Answers1

1

It seems like your helper only appends a fileValiditionError field to the request if the file is not an image. So if you are uploading a valid image there won't be a fileValiditionError field in the request. You should only check from the error the upload function returned. If there is an error you can return an error message to the client