【问题标题】:Express validator isIn function not work properlyExpress 验证器 isIn 功能无法正常工作
【发布时间】:2021-08-03 05:35:52
【问题描述】:

我对来自express-validatorisIn 函数有疑问,这是我的代码:

const genres = [
  "Comedy",
  "Fantasy",
  "Crime"
]


///
    body("genres")
      .exists()
      .withMessage("Genre is Required")
      .isArray()
      .withMessage("Genres must be an array of Strings")
      .isIn(genres)
      .withMessage("Genre contain invalid value.")

现在我解释一下什么是不正常的,

当我发送时:

{
    "genres":[ "Comedy", "Fantasy" ]
}

然后一切正常,我的验证器不会返回任何错误,

当我发送时:

{
    "genres":[ "Test" ]
}

然后验证器返回错误,这很好,

但是当我发送这个时:

{
    "genres":[ "Comedy", "Test" ]
}

那么...我的验证器不会返回任何错误,但他应该返回,因为我的 genres 数组中没有 Test 元素:/,有人可以告诉我这里有什么问题吗?看起来,验证器只需要从数组中返回一个正确的值即可在此处返回 true ...

这是我的验证器:

function validator(req, res, next) {
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    const extractedErrors = []
    errors.array().map(err => extractedErrors.push({ [err.param]: err.msg }))
  
    return res.json({
      errors: extractedErrors
    })
  }

  next();
}

感谢您的帮助!

【问题讨论】:

    标签: javascript typescript express validation


    【解决方案1】:

    express-validator 封装了validator.js 库,来自validator.js here的文档

    isIn(str, values) 检查字符串是否在允许值的数组中。

    源码here

    该方法仅适用于字符串,不适用于数组。看起来图书馆只关心数组中的第一项。这个输入给了我错误

    {
        "genres":[ "Test" , "Comedy"]
    }
    

    【讨论】:

    • 所以这是这个库中的一个错误,这不应该像这样工作
    • 我不这么认为。这是写在文档中的,所以它是预期的。无论如何,您都可以提出拉取请求或与他们讨论。
    • 此外:“Since validator.js only accepts string as input, any value (including arrays and objects) that needs to be validated by a Standard Validator is first converted to such type.”。这当然与isArray() 完全相反。不,它不仅仅关心数组中的第一项,它会将数组强制转换为字符串 - ["Test"] 变为 "Test"["Test", "Comedy"] 变为 "Test,Comedy"。看起来您需要一个 .custom() 验证器来检查数组的 每个 元素。
    • @Bergi,当我使用 ["Comedy, "Test"] 进行测试时,这不会返回任何错误。所以我认为数组不会强制转换为字符串。完全同意自定义验证器在这种情况下。
    【解决方案2】:

    使用options 代替genres,并使用逗号分隔的字符串代替数组。请参阅下面的示例

    {
        "options": "Test,Comedy"
    }
    

    如果您有array,您可以执行array.join(),请参阅here 了解更多信息

    【讨论】:

      猜你喜欢
      • 2013-06-23
      • 1970-01-01
      • 1970-01-01
      • 2013-02-07
      • 1970-01-01
      • 2020-03-22
      • 2017-09-23
      • 1970-01-01
      相关资源
      最近更新 更多