【问题标题】:Validate an array of object using express-validator使用 express-validator 验证对象数组
【发布时间】:2021-04-26 10:46:46
【问题描述】:

我正在使用express-validator 在 API 中验证我的请求正文。 我想验证一个请求字段 - dataPoints 它应该是一个对象数组。我想检查每个对象中是否有一个键 - dataType 并且它的值是数组的一部分 - ["selection", "number", "text", "date"]。这是我的代码

  validateParameters: () => {
    return [
      body("name").exists().withMessage("The name is required!"),
      body("description").exists().withMessage("The description is required"),
      body("dataPoints").isArray().withMessage("Datapoints can not be empty and must be an array!"),
      body("dataPoints").custom(async (value) => {
        if (value !== undefined & value.length > 0) {
          value.forEach(function (dataPoint) {
            var options = ["selection", "number", "text", "date"];
            let dataValue = dataPoint.dataType ? dataPoint.dataType : "";
            console.log(dataValue)
            if (options.indexOf(dataValue.toLowerCase()) !== -1) {
              return Promise.reject();
            }
          })
          .withMessage("Invalid data point");
        }
       
      }),
    ]
  },

当我通过错误的dataType 运行而不是Invalid data point 时,我目前收到此错误

{
    "status": "error",
    "errors": [
        {
            "message": "Cannot read property 'withMessage' of undefined"
        }
    ]
}

我该如何解决这个问题?

另外,我如何确保dataPoints数组在提交之前至少包含一个对象,因为目前可以提交一个空的,这是错误的!

【问题讨论】:

  • 我正在寻找如何在单个函数中使用所有验证而不是使用 body('username').isEmail(), body('password').isLength({ min: 5 }) 等。谁能帮忙?

标签: node.js express express-validator


【解决方案1】:

你应该在自定义验证器中使用 throw new Error 而不是 .withMessage 方法 这是一个例子:

    body("properties")
  .custom((value) => {
    if (_.isArray(value)) {
      if (value.length !== 0) {
        for (var i = 0; i < value.length; i++) {
          if (
            /^[ \u0600-\u06FF A-Za-z ][ \u0600-\u06FF A-Za-z ]+$/.test(
              value[i]
            )
          ) {
            if (i === value.length - 1) {
              return true;
            } else {
              continue;
            }
          } else {
            throw new Error("Invalid data point");
          }
        }
      } else {
        return true;
      }
    } else {
      throw new Error("Invalid data point");
    }
  })
  .optional(),

如果你想通过验证器,你应该返回 true

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-02-09
    • 2022-01-19
    • 2014-08-05
    • 2020-06-29
    • 1970-01-01
    • 1970-01-01
    • 2012-09-14
    相关资源
    最近更新 更多