如何解决express-validator在Node.js路由与控制器代码中失效问题?
Got it, let's sort out why your express-validator checks aren't stopping invalid data from being saved. The main issue is a tiny syntax mistake that's making your validation logic completely skip.
1. The Critical Bug: isEmpty Isn't Being Called
In your controllers/auth.js file, you're checking !errors.isEmpty — but isEmpty is a method, not a static property. Right now, you're just verifying that the method exists (which it always does), so the error handling block never runs, and invalid data slips through to the database.
Fixed Controller Code (controllers/auth.js)
const User = require("../models/user"); exports.signup = (req, res) => { const errors = validationResult(req); // Fix: Add parentheses to call the isEmpty() method if (!errors.isEmpty()) { return res.status(422).json({ error: errors.array()[0].msg }); } const user = new User(req.body); user.save((err, user) => { if (err) { return res.status(400).json({ err: "There is an error" }); } else { return res.json({ name: user.name, email: user.email, id: user._id }); } }); };
2. Clean Up Redundant Imports
You don't need to re-import express-validator in your controller — the validation rules are already defined in your route file, and validationResult correctly uses the request object passed from the route. Removing this extra import keeps your code cleaner.
Why This Fix Works
By adding parentheses to isEmpty(), you're actually running the validation check to see if there are any errors. Without them, your code skips the error handling entirely, allowing invalid data (like short names or bad emails) to be saved to the database.
Optional Quality-of-Life Improvement
If you want to let users fix multiple validation issues at once instead of one at a time, modify the error response to return all errors:
return res.status(422).json({ errors: errors.array() });
This way, the client gets feedback on all invalid fields (e.g., short name and invalid email) in one request.
内容的提问来源于stack exchange,提问作者SAMBHAV JAIN

