如何用express-validator验证文件输入?文件必填校验异常求助
Hey there! I get it, figuring out file validation with express-validator can be tricky when you're new to Express. Let's sort out why your avatar field is always throwing a "required" error, even when you upload a file.
The Root Cause
Here's the thing: when you use check('avatar').notEmpty(), express-validator looks for the avatar field in req.body by default. But when you use multer's upload.single('avatar'), the uploaded file data gets stored in req.file instead of req.body. That's why your validation always fails—express-validator can't find the file in the place it's checking!
The Fix: Custom Validator for Files
To fix this, we need to create a custom validator that checks directly for req.file instead of relying on the default body check. Here's how to update your code:
Updated app.post Route Code
app.post("/submitForm", upload.single('avatar'), [ check('name') .notEmpty().withMessage("Name is required"), check('email') .notEmpty().withMessage("Email is required") .isEmail().withMessage("Please enter a valid email address"), // Custom validation for the avatar file check('avatar') .custom((_, { req }) => { // Check if multer captured a file if (!req.file) { throw new Error('Profile Img is required'); } // Return true if validation passes return true; }) ], (req, res) => { const errors = validationResult(req); if (!errors.isEmpty()) { console.log(errors); res.render("./form", { errors: errors.array() }) } else { // Add your success logic here (e.g., save file metadata, redirect) res.send("Form submitted successfully with your profile image!"); } })
What This Does
- The
custom()validator gives us access to the request object (req) via its second parameter. - We check if
req.fileexists—if it doesn't, that means the user didn't upload a file, so we throw an error message. - If
req.fileis present, we returntrueto confirm the validation passed.
Quick Check
Make sure your HTML form's file input has the name attribute set to avatar (matching what you passed to upload.single('avatar')), like this:
<input type="file" name="avatar" />
That's it! Now your file required validation will work correctly—only throwing an error when the user doesn't select a file, and passing when they do.
内容的提问来源于stack exchange,提问作者Manish Joshi

