Search code examples
validationexpress

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


I am using express-validator for validation. In my controller I have a method for adding new pictures to the database. Here is my code:

function createPicture(req, res) {

req.checkBody('title', `The title can't be empty.`).notEmpty();
req.checkBody('image', 'You must select an image.').notEmpty();

let errors = req.validationErrors();

if (errors) {
    res.json({errors: errors});
} else { ... }

The code works for the title field however no matter if I select an image or not - I still get a validation error about it. How can I validate file input? I just want it to be required.


Solution

  • 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