Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 自定义验证查询始终激发-express validator_Node.js_Mongodb_Express_Mongoose - Fatal编程技术网

Node.js 自定义验证查询始终激发-express validator

Node.js 自定义验证查询始终激发-express validator,node.js,mongodb,express,mongoose,Node.js,Mongodb,Express,Mongoose,我正在尝试使用expressvalidator实现验证,只有当字段实际有一些输入时,它才应该启动。如果它是空的,就应该忽略它。验证的第一部分是检查字段是否符合regex要求,第二部分是检查数据库中是否存在该值。不允许使用大写字母的同一用户名的小写版本,即:Shirley和Shirley被视为同一事物 body('username') .trim() .custom((value, { req }) => { var regex = /^[a-zA-Z0-9]

我正在尝试使用expressvalidator实现验证,只有当字段实际有一些输入时,它才应该启动。如果它是空的,就应该忽略它。验证的第一部分是检查字段是否符合regex要求,第二部分是检查数据库中是否存在该值。不允许使用大写字母的同一用户名的小写版本,即:Shirley和Shirley被视为同一事物

body('username')
    .trim()
    .custom((value, { req }) => {
        var regex = /^[a-zA-Z0-9]{5,20}$/;
        if (value != '' && !value.match(regex)) {
            throw new Error('Username does not meet required criteria.');
        }
        return true;
    })
    .custom((value, { req }) => {
        if (value !== '') {
            return User.findOne({ username: new RegExp(`^${value}$`, 'i') })
                .then(userDoc => {
                    if (userDoc) {
                        return Promise.reject('Username unavailable');
                    }
                    return true;
                });
        }
    }),

如果我将username字段留空,我仍然会收到一个验证错误,告诉我“username unavailable”

设法让它像这样工作

  .custom(value => {
        if (value !== '') {
            return User.findOne({ username: new RegExp(`^${value}$`, 'i') })
                .then(userDoc => {
                    if (userDoc) {
                        return Promise.reject('Username not available');
                    } else {
                        return true;
                    }
                })
        } else {
            return true;
        }
    })

所以您有一个基于
不完全等于
的条件。在这种情况下,
value
的值到底是多少?当然,这是您测试的第一件事。@KevinB,如果我的console.log值为空,那么在我的visual studio代码终端中只有一个空行,所以它是空的。对不起,是的。我正在查看我的旧版本,它是
if(value)
@KevinB,我添加了一些代码来检查,在控制台中我得到消息:“value is empty”。
if(value!=''){console.log('value is notempty');}否则if(value===''{console.log('value is empty');}
传递给custom的回调是否需要返回值?(文档在哪里?)