【问题标题】:How to validate file input in express validator?如何在快速验证器中验证文件输入?
【发布时间】:2020-09-18 00:44:46
【问题描述】:

我正在使用 express 验证器进行验证,在我的代码中,其他文本字段(例如姓名和电子邮件)正在正确验证,但问题在于输入文件字段。我想检查空文件。 我是快递的新手,请帮助我。我的代码如下:

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");
})

该代码适用于名称和电子邮件字段,但是无论我是否选择图像 - 我仍然会收到有关它的验证错误。如何验证文件输入?我只是希望它是必需的。

【问题讨论】:

    标签: javascript node.js express multer express-validator


    【解决方案1】:

    Express 验证器无法直接验证文件。一种简单快捷的解决方案是在另一个属性中使用custom validator

    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;
        }),
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-25
      • 1970-01-01
      • 2016-04-30
      • 1970-01-01
      相关资源
      最近更新 更多