问题描述
如何为依赖其他字段信息的 express-validator
编写自定义验证?
示例问题:
我有一个心愿单应用程序,用户可以在其中为心愿单所有者购买商品。他们可以在该项目上留下便条。备注的字符数必须少于商品的价格。
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;
?有没有办法在 req.body
中间件中访问 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',(req,res,next) => {
const errors = validationResult(req).array();
if (errors.length) {
return res.status(400).send(errors);
}
return next();
},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);
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)