javascript - 快速验证器 : How to make conditional validations based on other fields?

标签 javascript node.js express express-validator

如何为依赖其他字段信息的 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/

相关文章:

javascript - 如何在react中为不同的组件使用不同的 header

javascript - material-ui useScrollTrigger 与子目标 ref 的用法是什么?

javascript - graphqlHTTP 不是函数

node.js - 从redis key nodejs弹出值的原子操作

node.js - 在 Callable Firebase Functions 中获取请求 URL

javascript - 当单击页面中的任何按钮时,将在使用 Jquery-File-Upload 时打开文件对话框

node.js - Node Js 中的 OrientDB 分页

javascript - 修改其他用户的对象时 Express 返回 "User is not authorized"

javascript - Express 路由器 : Router. use() 需要一个中间件函数但得到一个对象

javascript - 如何过滤表格并仅显示 <td> 值而不是 <tr> 值?