首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >快速验证器-自定义密码验证器无法读取未定义的属性。

快速验证器-自定义密码验证器无法读取未定义的属性。
EN

Stack Overflow用户
提问于 2018-07-10 07:43:53
回答 1查看 3.4K关注 0票数 1

我有一个简单的验证器,它检查"password“= "passwordconf”

exports.RegisterUser =[

代码语言:javascript
复制
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!')
                }                      
        })}

}]

如果我评论一下这句话,

代码语言:javascript
复制
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复制了这条语句,我在保存新用户时给出了这个错误

代码语言:javascript
复制
{"errors":[{"location":"body","param":"passwordconf","value":"password1","msg":"Cannot read property 'then' of undefined"}]}

这里少了什么?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-07-11 02:01:24

这是已知的臭虫,并将在下一个版本中修复(当前版本是v5.2.0)。

自定义验证器如果不返回任何错误,就会失败。

要解决这个问题,只需从验证器返回true

代码语言:javascript
复制
check('passwordconf').custom((value , { req }) => {
    if (value !== req.body.password) {
        throw new Error('Password confirmation is incorrect');
    }

    return true;
})
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51259708

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档