Manish Joshi
Manish Joshi

Reputation: 31

How to validate file input in express validator?

i am using express validator for validation, in my code other text fields like name and email are validating properly but problem is with input file field. i want to check against empty file. I am new Lerner of express, help me anybody. my code are below :

app.js

const express = require("express");
const path = require("path");
const bodyParser = require("body-parser");
const { check, validationResult } = require("express-validator");
const multer = require("multer");

var upload = multer({ dest: 'uploads/' })

const app = express();

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');


app.use(express.static(path.join(__dirname, 'public')));

app.use(bodyParser.urlencoded({ extended: false }));


app.use(bodyParser.json());

app.get("/", (req, res) => {
    res.render("./form");
});



app.post("/submitForm", upload.single('avatar'), [
    check('name')
        .notEmpty().withMessage("Name is required"),
    check('email')
        .notEmpty().withMessage("Email are required")
        .isEmail().withMessage("Plese enter a valid email address"),
    check('avatar')
        .notEmpty().withMessage("Profile Img is required")
], (req, res) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
        console.log(errors);
        res.render("./form", {
            errors: errors.array()
        })
    }
})

app.listen(3000, (req, res) => {
    console.log("port listen on 3000");
})

The code works for the name and email 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.

Upvotes: 3

Views: 4393

Answers (2)

Hong Phuc
Hong Phuc

Reputation: 83

In fact, express-validator doesn't support file validation but you can implement it with this workaround.

app.post(
  '/submitForm',
  upload.single('avatar'),
  (req, res, next) => {
    req.body.avatar = req.file.avatar

    next()
  }),
  [
    check('name').notEmpty().withMessage('Name is required'),
    check('email')
      .notEmpty()
      .withMessage('Email are required')
      .isEmail()
      .withMessage('Plese enter a valid email address'),
    check('avatar').notEmpty().withMessage('Avatar is required'),
  ],
  (req, res) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      console.log(errors);
      res.render('./form', {
        errors: errors.array(),
      });
    }
  }
);

Upvotes: 0

dimitris tseggenes
dimitris tseggenes

Reputation: 3186

Express validator can't validate files directly. One simple and quick solution is to use a custom validator inside another property.

check('name')
    .not().isEmpty().withMessage("Name is required")
    // Here you check that file input is required
    .custom((value, { req }) => {
        if (!req.file) throw new Error("Profile Img is required");
        return true;
    }),

Upvotes: 3

Related Questions