我有一个简单的验证器,它检查"password“= "passwordconf”
exports.RegisterUser =[
check('username').isLength({ min: 1 , max: 10}).trim().withMessage("Length 1-10"),
check('password').isLength({ min: 6 , max: 10}).trim().withMessage("Length 6-10"),
check('passwordconf').isLength({ min: 6 , max: 10}).trim().withMessage("Length 6-10"),
check('passwordconf').custom((value , { req }) => {
if (value !== req.body.password) {
throw new Error('Password confirmation is incorrect');
}
}),
sanitizeBody('*').trim().escape(),
function ( req , res ) {
//check for errors
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(422).json({ errors: errors.array() });
} else {
var user = new User({
username : req.body.username,
password : req.body.password
});
var username = req.body.username;
//check if user is in DB
User.findOne({ 'username' : username})
.exec(( err , docs) => {
if (err) {
res.send('There was an error');
return err;
} else if (!docs) {
//username does not exist
user.save((err) => {
if (err) {
return next(err)
} else {
//saved it
res.send('saved a new user!')
}
})
} else {
res.send('Username exists!')
}
})}}]
如果我评论一下这句话,
check('passwordconf').custom((value , { req }) => {
if (value !== req.body.password) {
throw new Error('Password confirmation is incorrect');
}
})代码工作。我从正式文档https://express-validator.github.io/docs/custom-validators-sanitizers.html复制了这条语句,我在保存新用户时给出了这个错误
{"errors":[{"location":"body","param":"passwordconf","value":"password1","msg":"Cannot read property 'then' of undefined"}]}这里少了什么?
发布于 2018-07-11 02:01:24
这是已知的臭虫,并将在下一个版本中修复(当前版本是v5.2.0)。
自定义验证器如果不返回任何错误,就会失败。
要解决这个问题,只需从验证器返回true:
check('passwordconf').custom((value , { req }) => {
if (value !== req.body.password) {
throw new Error('Password confirmation is incorrect');
}
return true;
})https://stackoverflow.com/questions/51259708
复制相似问题