后端: 添加输入验证中间件

This commit is contained in:
Backend Developer 2026-03-10 09:37:24 +00:00
parent 3da2482f18
commit f791aa710a

View File

@ -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;