快速验证器检查输入是否是可用选项之一

Express validator check if input is one of the options available

目前我有html这样的代码:

<!DOCTYPE html>
<html>
<body>

<p>Select an element</p>

<form action="/action">
  <label for="fruit">Choose a fruit:</label>
  <select name="fruit" id="fruit">
    <option value="Banana">Banana</option>
    <option value="Apple">Apple</option>
    <option value="Orange">Orange</option>
  </select>
  <br><br>
  <input type="submit" value="Submit">
</form>


</body>
</html>

在服务器端,我想与快速验证器核实 post 请求中的水果是香蕉、苹果还是橙子。 这是我到目前为止的代码:

const{body} = require('express-validator');

const VALIDATORS =  {
    Fruit: [
        body('fruit')
            .exists()
            .withMessage('Fruit is Requiered')
            .isString()
            .withMessage('Fruit must be a String')
    ]
}

module.exports = VALIDATORS;

如何检查POST请求发送的字符串是否是所需的水果之一?

您可以通过 .custom 函数实现;

例如:

body('fruit').custom((value, {req}) => {
  const fruits = ['Orange', 'Banana', 'Apple'];
  if (!fruits.includes(value)) {
    throw new Error('Unknown fruit type.');
  }

  return true;
})

由于 express-validator 是基于 validator.js 的,因此您可以使用这种情况的方法应该已经可用。无需自定义验证方法。

validator.js 文档,检查字符串是否在允许值数组中:

isIn(str, values)

您可以在验证链中使用它 API,在您的情况下:

body('fruit')
 .exists()
 .withMessage('Fruit is Requiered')
 .isString()
 .withMessage('Fruit must be a String')
 .isIn(['Banana', 'Apple', 'Orange'])
 .withMessage('Fruit does contain invalid value')

这个方法也包含在express-validator文档中,这里 https://express-validator.github.io/docs/validation-chain-api.html#not(在not方法的例子中使用)