Express - How to validate file input with express-validator?

I had the same problem, the below code will not work since express-validator only validates strings

req.checkBody('title', 'The title can't be empty.').notEmpty();

req.checkBody('image', 'You must select an image.').notEmpty();

You'll need to write a custom validator, express-validator allows for this, okay this is an example of one

//requiring the validator
var expressValidator = require('express-validator');
//the app use part
app.use(expressValidator({
customValidators: {
    isImage: function(value, filename) {

        var extension = (path.extname(filename)).toLowerCase();
        switch (extension) {
            case '.jpg':
                return '.jpg';
            case '.jpeg':
                return '.jpeg';
            case  '.png':
                return '.png';
            default:
                return false;
        }
    }
}}));

To use the custom validator, do this first to make sure empty files will not throw undefined error:

restLogo = typeof req.files['rest_logo'] !== "undefined" ? req.files['rest_logo'][0].filename : '';

Finally to use your custom validator:

req.checkBody('rest_logo', 'Restaurant Logo - Please upload an image Jpeg, Png or Gif').isImage(restLogo);

Thanks for your question, hope this will help someone


In order to validate a file input field you could use multer: middleware that adds a body object and a file object to the request object.
And then use express-validator .custom() validation function chained to your validation middleware.

With multer the user inputs are accessible through req.file for the file input field and req.bodyfor the other input fields (if there is any).

req.file will return an object containing the 6 following fields: (example for a pdf)

{
  fieldname: 'fileInputFieldName',
  originalname: 'uploaded_file.pdf',
  encoding: '7bit',
  mimetype: 'application/pdf',
  buffer: <Buffer 2 ... 192685 more bytes>,
  size: 192735
}

Let's say you only want to accept pdf files: you could validate against the mimetype of the uploaded file, (which is accessible with: req.file.mimetype):

// express-validator import
const { check, validationResult } = require('express-validator'); 

// multer import and setup
const multer = require('multer');
const storage = multer.memoryStorage(); // Holds a buffer of the file in memory
const upload = multer({ storage: storage });


exports.post_file = [
// multer middleware
upload.single('fileInputFieldName'),


// express-validator middleware
check('fileInputFieldName')
.custom((value, {req}) => {
        if(req.files.mimetype === 'application/pdf'){
            return '.pdf'; // return "non-falsy" value to indicate valid data"
        }else{
            return false; // return "falsy" value to indicate invalid data
        }
    })
.withMessage('Please only submit pdf documents.'), // custom error message that will be send back if the file in not a pdf. 


// process the request with validated user inputs
(res, req, next) => {
    ...
    ...
}
]