如何在快速验证器中验证文件输入? [英] How to validate file input in express validator?

查看:50
本文介绍了如何在快速验证器中验证文件输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用快速验证器进行验证,在我的代码中,名称和电子邮件等其他文本字段正在正确验证,但问题在于输入文件字段.我想检查空文件.我是快递的新勒纳,任何人都可以帮助我.我的代码如下:

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.

推荐答案

Express 验证器无法直接验证文件.一种简单快捷的解决方案是在内部使用 自定义验证器另一个属性.

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

这篇关于如何在快速验证器中验证文件输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆