question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

express-validator can not validate while using multer

See original GitHub issue

whenever I submit my form with empty values the express-validator works fine and sends the validation errors, however when I also submit the form with NOT EMPTY VALUES I get errors too, I’m really confused about what’s wrong with this code?

const {check, validationResult} = require('express-validator');
var multer = require('multer');
var upload = multer({dest: 'uploads/'});

router.post(
    '/add',
    [
        check('title', 'title field is required').not().isEmpty(),
        check('text', 'text field is required').not().isEmpty()
    ],
    upload.single('mainImage'),
    (req, res) =>{

        const validationErrors = validationResult(req);

        if(!validationErrors.isEmpty()){
            // in every situation, only this part of code is going to be executed
            return res.status(422).json({errors: validationErrors.array()});
        }else{
            // inserting into DB
            res.send();
        }
});

Issue Analytics

  • State:open
  • Created 4 years ago
  • Comments:12 (3 by maintainers)

github_iconTop GitHub Comments

13reactions
nico-soricecommented, May 3, 2020

@Alirezaies

Hi, i know its a little bit late, but since this is one of the first search results for this issue, one way to do it’s using “checkSchema” to check for basically anything in the request object.

You can do something like this:

const multer = require('multer');

const upload = multer({
    limits: {fileSize: 10 * Math.pow(1024, 2 /* MBs*/)},
    fileFilter(req, file, cb){
        //Validate the files as you wish, this is just an example
        cb(null, file.mimetype === 'application/pdf');
    },
});

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

app.post('/test', [
    upload.fields([
        {name: 'resume_file', maxCount: 1},
        {name: 'another_file', maxCount: 3},
    ]),
    check('email', 'Email field is invalid, etc etc').not().isEmpty().isEmail().isLength({max: 255}),
    checkSchema({
        'resume_file': {
            custom: {
                options: (value, { req, path }) => !!req.files[path],
                errorMessage: 'You should upload a PDF file up to 10Mb',
            },
        },
        'another_file': {
            custom: {
                options: (value, { req, path }) => !!req.files[path] && req.files[path].length >= 2,
                errorMessage: 'You should upload at least two PDF files, up to 10Mb',
            },
        },
    }),
    (req, res, next) => {
        const errors = validationResult(req);

        if(!errors.isEmpty()){
            return res.status(422).json({
                message: 'Request fields or files are invalid, but im handling all of them together!',
                errors: errors.array(),
            })
        }

        //Your route logic, knowing that both the fields, and the files are valid

        return res.status(200).json({
            message: 'Request fields and files are valid!',
        })
    }
]);

And now you can have all your errors messages handled by express-validator, while the file will only be uploaded if it is a valid file acording to your multer fileFilter.

Bear in mind that if you’re using multer.only(field), etc, you will have to change the custom options in the validator accordingly, since .only will make the only file available at req.file, instead of at req.file[path].

8reactions
Alirezaiescommented, Oct 14, 2019

by using upload.single('mainImage') before the check(), no validation error will be produced by express-validator, but if I put the upload.single('mainImage') after the check() I get validation errors on both empty and filled form.

StackOverflow didn’t help at all

Read more comments on GitHub >

github_iconTop Results From Across the Web

Multer and express-validator creating problem in validation
But with multer this will not happen - you will be able to access body fields like description and name and then do...
Read more >
Express-validator not working after multer function : r/node
I have a form with some text inputs and a file input, I handle the file upload with multer and I'm trying to...
Read more >
Multer File Type Validation Tutorial with Example - positronX.io
Today we are going to learn, how to validate file types while uploading files with Multer. In this tutorial, we will understand how...
Read more >
Top 5 express-validator Code Examples - Snyk
Use Snyk Code to scan source code in minutes - no build needed - and fix issues ... app.post('/posts/new', [ check('postTitle', 'Title must...
Read more >
Handling File Uploads in Node.js with Express and Multer
That's everything we need on the view side. Validation and Sanitization. There is a handy middleware express-validator for validating and sanitizing data using...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found