56 lines
1.4 KiB
JavaScript
56 lines
1.4 KiB
JavaScript
const { body, validationResult } = require('express-validator');
|
|
|
|
// 注册验证规则
|
|
const registerValidation = [
|
|
body('username')
|
|
.isLength({ min: 3, max: 50 })
|
|
.withMessage('用户名长度必须在3-50个字符之间')
|
|
.matches(/^[a-zA-Z0-9_]+$/)
|
|
.withMessage('用户名只能包含字母、数字和下划线'),
|
|
|
|
body('email')
|
|
.isEmail()
|
|
.withMessage('请输入有效的邮箱地址')
|
|
.normalizeEmail(),
|
|
|
|
body('password')
|
|
.isLength({ min: 6 })
|
|
.withMessage('密码长度至少6个字符')
|
|
.matches(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)/)
|
|
.withMessage('密码必须包含至少一个小写字母、一个大写字母和一个数字')
|
|
];
|
|
|
|
// 登录验证规则
|
|
const loginValidation = [
|
|
body('username')
|
|
.notEmpty()
|
|
.withMessage('用户名不能为空'),
|
|
|
|
body('password')
|
|
.notEmpty()
|
|
.withMessage('密码不能为空')
|
|
];
|
|
|
|
// 验证结果处理中间件
|
|
const handleValidationErrors = (req, res, next) => {
|
|
const errors = validationResult(req);
|
|
// console.log(req.body);
|
|
|
|
if (!errors.isEmpty()) {
|
|
return res.status(400).json({
|
|
success: false,
|
|
message: '输入验证失败',
|
|
errors: errors.array().map(error => ({
|
|
field: error.path,
|
|
message: error.msg
|
|
}))
|
|
});
|
|
}
|
|
next();
|
|
};
|
|
|
|
module.exports = {
|
|
registerValidation,
|
|
loginValidation,
|
|
handleValidationErrors
|
|
}; |