如何为依赖其他字段信息的 express-validator
编写自定义验证?
示例问题:
我有一个愿望 list 应用程序,用户可以在其中为愿望 list 所有者购买商品。他们可以在该元素上留下便条。备注的字符数必须少于商品的价格。
Post Request: "/purchase"
Body: {
"itemId": "1",
"note": "I'm buying this to say thank you for your help with my Chinese practice. You helped me understand tones better."
}
在数据库中,ID 为 1 的商品为 100 美元。此注释有 111 个字符。 111 大于 100,因此不应验证。
我无法弄清楚如何使用 express-validator
访问自定义验证器中的其他字段,因此我无法弄清楚如何编写此验证。
我可以成功地将注释长度限制为恒定长度,例如 100 个字符。但是如何使该字符长度值等于商品的价格:data.items.find((i) => i.itemId === +req.body.itemId).price;
?有没有办法在 body()
中间件中访问 req.body
?
body('note', `Note must be 100 or less characters`).custom((note) => note.length <= 100),
完整代码:
const { body, validationResult } = require('express-validator');
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const data = {
items: [
{ itemId: 1, price: 100 },
{ itemId: 2, price: 50 },
],
};
app.use(bodyParser.json());
app.post(
'/purchase',
body('note', `Note must be 100 or less characters`).custom((note) => note.length <= 100),
(req, res, next) => {
const errors = validationResult(req).array();
if (errors.length) {
return res.status(400).send(errors);
}
return next();
},
(req, res, next) => {
const itemPrice = data.items.find((i) => i.itemId === +req.body.itemId).price;
res.status(200).send({
message: `Item ${req.body.itemId} purchased for $${itemPrice}`,
});
}
);
app.listen(3500);
最佳答案
我发现您可以将请求对象传递给自定义验证器。
const { body, validationResult } = require('express-validator');
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const data = {
items: [
{ itemId: 1, price: 100 },
{ itemId: 2, price: 50 },
],
};
app.use(bodyParser.json());
app.post(
'/purchase',
body('note', `Note too long.`).custom(
(note, { req, location, path }) =>
note.length <= data.items.find((i) => i.itemId === +req.body.itemId).price
),
(req, res, next) => {
const errors = validationResult(req).array();
if (errors.length) {
const noteError = errors.find((err) => err.msg === 'Note too long.');
if (noteError)
noteError.msg = `Note must be less than ${
data.items.find((i) => i.itemId === +req.body.itemId).price
} characters`;
return res.status(400).send(errors);
}
return next();
},
(req, res, next) => {
const itemPrice = data.items.find((i) => i.itemId === +req.body.itemId).price;
res.status(200).send({
message: `Item ${req.body.itemId} purchased for $${itemPrice}`,
});
}
);
app.listen(3500);
此示例的引用链接位于:the official express-validator docs
关于javascript - 快速验证器 : How to make conditional validations based on other fields?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65908610/