From f791aa710aca20ee9a4ac015e790162a19858226 Mon Sep 17 00:00:00 2001 From: Backend Developer Date: Tue, 10 Mar 2026 09:37:24 +0000 Subject: [PATCH] =?UTF-8?q?=E5=90=8E=E7=AB=AF:=20=E6=B7=BB=E5=8A=A0?= =?UTF-8?q?=E8=BE=93=E5=85=A5=E9=AA=8C=E8=AF=81=E4=B8=AD=E9=97=B4=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/src/middleware/validate.js | 39 ++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 backend/src/middleware/validate.js 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;