我正在注册一个用户,我需要名称
、电子邮件
和密码
。
当没有给定名称
时,后端不需要检查电子邮件是否有效。
据我所知,这就是 the .bail()
functionality来自express-validator
。不幸的是,在我的情况下,此功能没有任何作用,所有验证都会运行。
路线:app.post('/register', validate(createUserSchema), createUser)
;
validate()
函数:
export const validate = (schemas: ValidationChain[]) => async (req: Request, res: Response, next: NextFunction) => {
await Promise.all(schemas.map(async (schema) => await schema.run(req)));
const result = validationResult(req);
if (result.isEmpty()) {
return next();
}
const errors = result.array();
return res.status(422).json(errors);
};
createUserSchema
:
export const createUserSchema = [
body('name', 'Name is required').notEmpty().bail(),
body('email', 'Email is required').notEmpty().bail(),
body('email').isEmail().withMessage('Email is not valid').bail(),
body('email')
.custom((value) => {
if (!value) return true;
return prisma.user
.findUnique({
where: {
email: value
}
})
.then(async (user) => {
if (user) {
return await Promise.reject(new Error('E-mail already in use'));
}
return await Promise.resolve();
});
}).bail(),
body('password', 'Password is required').notEmpty().bail()
.isLength({min: 6}).withMessage('Password must be longer than 6 characters')
.matches(/[A-Z]/).withMessage('Password does not contain an uppercase character')
.matches(/\W/).withMessage('Password does not contain any non-word characters')
];
我的请求负载:
{
name: "",
email: "",
password: ""
}
我得到的回复:
[
{
"value":"",
"msg":"Name is required",
"param":"name",
"location":"body"
},
{
"value":"",
"msg":"Email is required",
"param":"email",
"location":"body"
},
{
"value":"",
"msg":"Email is not valid",
"param":"email",
"location":"body"
},
{
"value":"",
"msg":"Password is required",
"param":"password",
"location":"body"
}
]
我期望的响应(因为它应该在第一次验证时放弃):
[
{
"value":"",
"msg":"Name is required",
"param":"name",
"location":"body"
}
]
我做错了什么吗?
最佳答案
在这里回答我自己的问题-_-
所以我误解了 express-validator
中的验证链
是什么。
我的印象是不同验证行形成一个验证链(因此一个数组将形成一个链)。不是这种情况。 一条链由单独的验证规则形成。
例如
export const createUserSchema = [
body('name').notEmpty().withMessage('Name is required').bail(), //<--- this is a validation chain
body('email').notEmpty().withMessage('Email is required').bail()
.isEmail().withMessage('Email is not valid').bail()
]; // <--- The whole array does not form a chain (which is what I thought)
Gustavo Henke 解释了它 here .
因此,为了实现我想要的目标,我需要使用 .if(condition)
验证。
关于typescript - .bail() 不适用于快速验证器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66931491/