在快速验证中将字符串与数组中的值匹配

2fa*_*.TV 4 validation node.js express

我正在使用express-validator来验证对我的API的输入,但是在理解match函数时遇到了一些问题。我基本上需要能够确定一个字符串是否与可接受值数组中的任何值匹配,如下所示,但是它似乎不起作用。有什么建议么?

var schema = {
  "role": {
    in: 'body',
    matches: {
      options: ["administrator", "editor", "contributor", "user"],
      errorMessage: "Invalid role"
    }
  }
}

req.check(schema)
Run Code Online (Sandbox Code Playgroud)

小智 8

作为替代方案,您可以使用此架构:

 var schema = {
  "role": {
    in: 'body',
    isIn: {
      options: [["administrator", "editor", "contributor", "user"]],
      errorMessage: "Invalid role"
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

更多关于这个问题


Jas*_*n G 7

我这样做的方法是使用isIn()

check('action').isIn(['like', 'dislike']).run(req)
Run Code Online (Sandbox Code Playgroud)


mkh*_*yan 5

matches.options构造一个正则表达式。您可以将正则表达式作为数组的第一个元素传递。尝试这个:

var schema = {
  "role": {
    in: 'body',
    matches: {
      options: [/\b(?:administrator|editor|contributor|user)\b/],
      errorMessage: "Invalid role"
    }
  }
}
Run Code Online (Sandbox Code Playgroud)