const { body, query, param, validationResult } = require('express-validator'); // 验证结果处理 function validate(req, res, next) { const errors = validationResult(req); if (!errors.isEmpty()) { return res.status(400).json({ error: '输入验证失败', details: errors.array().map(e => ({ field: e.path, message: e.msg })) }); } next(); } // 注册验证 const registerRules = [ body('username') .trim() .isLength({ min: 3, max: 20 }).withMessage('用户名3-20个字符') .matches(/^[a-zA-Z0-9_]+$/).withMessage('用户名只能包含字母、数字、下划线'), body('password') .isLength({ min: 6 }).withMessage('密码至少6个字符'), ]; // 登录验证 const loginRules = [ body('username').trim().notEmpty().withMessage('用户名不能为空'), body('password').notEmpty().withMessage('密码不能为空'), ]; // 彩票创建验证 const ticketCreateRules = [ body('type').isIn(['welfare', 'sports']).withMessage('无效的彩票类型'), body('game').isString().notEmpty().withMessage('游戏类型不能为空'), body('cost').isFloat({ min: 0 }).withMessage('金额必须为正数'), body('issue').optional().matches(/^\d{5,}$/).withMessage('期号格式不正确'), body('numbers').optional().isArray().withMessage('号码必须是数组'), body('bet_count').optional().isInt({ min: 1 }).withMessage('注数必须大于0'), body('multiple').optional().isInt({ min: 1, max: 99 }).withMessage('倍数必须在1-99之间'), ]; // 彩票更新验证 const ticketUpdateRules = [ body('type').optional().isIn(['welfare', 'sports']).withMessage('无效的彩票类型'), body('game').optional().isString().notEmpty().withMessage('游戏类型不能为空'), body('cost').optional().isFloat({ min: 0 }).withMessage('金额必须为正数'), body('issue').optional().matches(/^\d{5,}$/).withMessage('期号格式不正确'), body('bet_count').optional().isInt({ min: 1 }).withMessage('注数必须大于0'), body('multiple').optional().isInt({ min: 1, max: 99 }).withMessage('倍数必须在1-99之间'), body('status').optional().isIn(['pending', 'won', 'lost']).withMessage('状态无效'), ]; // 开奖查询验证 const lotteryQueryRules = [ query('game').isString().notEmpty().withMessage('彩票类型不能为空'), query('issue').matches(/^\d{5,}$/).withMessage('期号格式不正确'), ]; // ID参数验证 const idParamRule = [ param('id').isInt({ min: 1 }).withMessage('无效的ID'), ]; module.exports = { validate, registerRules, loginRules, ticketCreateRules, ticketUpdateRules, lotteryQueryRules, idParamRule };