Express Validator:如何根据其他字段进行条件验证?

Express Validator: How to make conditional validations based on other fields?

如何编写依赖于其他字段信息的 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;?有没有办法在 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);

对此示例的引用 link 位于:the official express-validator docs