簡體   English   中英

快速驗證器檢查輸入是否是可用選項之一

[英]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>

在服務器端,我想通過 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 請求發送的字符串是否是必需的水果之一?

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

您可以通過.custom function 來實現;

例如:

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

  return true;
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM