![](/img/trans.png)
[英]Use Express validator version 6.4.0 along with express upload.Check validation of input before executing a post on route
[英]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.