后端: 添加输入验证中间件
This commit is contained in:
parent
3da2482f18
commit
f791aa710a
39
backend/src/middleware/validate.js
Normal file
39
backend/src/middleware/validate.js
Normal 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;
|
||||||
Loading…
Reference in New Issue
Block a user