【问题标题】:Express validator check if input is one of the options available快速验证器检查输入是否是可用选项之一
【发布时间】:2021-01-21 17:48:06
【问题描述】:

目前我有这样的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>

在服务器端,我想通过 express 验证器检查 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 请求发送的字符串是否是必需的水果之一?

【问题讨论】:

  • 您可以使用.matches() 方法,例如:.matches('Apple')

标签: javascript node.js express validation server-side


【解决方案1】:

由于 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方法)

【讨论】:

  • 谢谢!这对我帮助很大!
【解决方案2】:

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

例如:

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

  return true;
})

【讨论】:

    猜你喜欢
    • 2020-04-27
    • 1970-01-01
    • 1970-01-01
    • 2019-07-09
    • 1970-01-01
    • 2014-11-06
    • 2018-12-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多