diff --git a/backend/src/middleware/validate.js b/backend/src/middleware/validate.js new file mode 100644 index 0000000..1ca882d --- /dev/null +++ b/backend/src/middleware/validate.js @@ -0,0 +1,39 @@ +// 输入验证中间件 +const validate = (schema) => { + return (req, res, next) => { + const errors = []; + + for (const [field, rules] of Object.entries(schema)) { + const value = req.body[field]; + + if (rules.required && !value) { + errors.push(`${field} is required`); + continue; + } + + if (rules.type === 'string' && typeof value !== 'string') { + errors.push(`${field} must be a string`); + } + + if (rules.type === 'number' && typeof value !== 'number') { + errors.push(`${field} must be a number`); + } + + if (rules.minLength && value?.length < rules.minLength) { + errors.push(`${field} must be at least ${rules.minLength} characters`); + } + + if (rules.maxLength && value?.length > rules.maxLength) { + errors.push(`${field} must be at most ${rules.maxLength} characters`); + } + } + + if (errors.length > 0) { + return res.status(400).json({ error: errors.join(', ') }); + } + + next(); + }; +}; + +module.exports = validate;