问题描述
我正在注册一个需要 name
、email
和 password
的用户。
当没有 name
时,后端不需要检查电子邮件是否有效。
据我所知,这就是 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","msg":"Email is not valid","msg":"Password is required","param":"password","location":"body"
}
]
我期望的响应(因为它应该在第一次验证时保释):
[
{
"value":"","location":"body"
}
]
我做错了吗?
解决方法
在这里回答我自己的问题-_-
所以我误解了 Validation Chain
中的 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)
验证。