Gol*_*ova 7 javascript validation server-side node.js express
目前我有这样的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>
Run Code Online (Sandbox Code Playgroud)
在服务器端,我想通过快速验证器检查发布请求中的水果是否是香蕉、苹果或橙子。这是我到目前为止的代码:
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;
Run Code Online (Sandbox Code Playgroud)
如何检查POST请求发送的字符串是否是所需的水果之一?
Pas*_*ers 23
由于express-validator是基于validator.js,因此您可以用于这种情况的方法应该已经可用。不需要自定义验证方法。
从validator.js文档中,检查字符串是否在允许值的数组中:
isIn(str, values)
Run Code Online (Sandbox Code Playgroud)
您可以在验证链 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')
Run Code Online (Sandbox Code Playgroud)
此方法也包含在express-validator文档中,此处
https://express-validator.github.io/docs/validation-chain-api.html#not(在该方法的示例中使用not)
| 归档时间: |
|
| 查看次数: |
14620 次 |
| 最近记录: |