I use the express-validator
to check text fields and multer
to check avatars. But I have a problem, the express-validator
stopped checking the text fields, if you leave the field empty, the express validator will not give an error message that the field is empty.
I displayed text fields in a separate variable:
import { check, validationResult } from 'express-validator/check';
const validatorSignup = [
check('user_name').exists().isLength({ min: 4, max: 20 }),
....
];
Next, I want to check at registration whether all fields are filled by the user and whether the avatar is loaded:
router.post('/signup', (req, res) => {
try {
upload(req, res, validatorSignup, (err) => {
console.log(req.body)
const errors = validationResult(req.body);
if (!errors.isEmpty()) {
return res.status(422).json({
err: errors.array()
});
}
....
} catch (err) {
return res.status(500).json({
err: err
});
}
});
But I get an error:
onFinished(req, function () { next(err) })
^
TypeError: next is not a function
Help solve my problem.
The call sequence are messed up, there are two things being wrong here:
upload
is async and try catch will not work any way.
upload
is to be used like middleware and you cannot pass validatorSignup
like this expecting multer to do the validation. This is why an error is thrown for onFinished because multer expects third argument to be of (next)=>{}
, not an array.
Therefore your markup should be more like this:
router.post('/signup', upload, validatorSignup, (req, res) => {
console.log(req.body)
const errors = validationResult(req.body);
if (!errors.isEmpty()) {
return res.status(422).json({
err: errors.array()
});
}
...
});
Note1: I have not seen validationResult(req.body);
from documentation, only validationResult(req);
.
Note2: by default errors in middleware like upload
and validatorSignup
will automatically result in 500, if you want to customize the error message (like your JSON with err), check out Express error handling (Writing error handlers)