我正在使用快递验证器来验证我的字段。但是现在我有2或3个对象的数组,其中包含“ userId”和“ Hours”字段,如下所示。
[
{
user_id:1,
hours:8
},
{
user_id:2,
hours:7
}
]
Run Code Online (Sandbox Code Playgroud)
现在我需要验证,是否任何对象属性(例如小时或user_id)为空。如果为空则抛出错误。
Nav*_*ari 16
我可以使用这样的通配符来做到这一点:
app.post('/users', [
body().isArray(),
body('*.user_id', 'user_idfield must be a number').isNumeric(),
body('*.hours', 'annotations field must a number').exists().isNumeric(),
], (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(422).json({errors: errors.array()});
}
return res.status(200).json(req.body)
Run Code Online (Sandbox Code Playgroud)
Luc*_*edo 10
对于任何想要使用 checkSchema 验证对象数组的人,这里有一个示例,其中我正在验证可以包含 0 个项目的对象数组。如果您抛出一个函数来执行自定义验证,您甚至可以执行自定义验证:
JSON:
{
"employees": [
{
"roleId": 3,
"employeeId": 2,
},
{
"roleId": 5,
"employeeId": 4,
},
]
}
Run Code Online (Sandbox Code Playgroud)
检查架构:
const customValidator = (async (employees, { req }) => {
// employees will always be an array,
// given the bail property that will make
// the code to never reach the custom validator
// if the isArray validator fails
if(!something) {
throw Error('employee error');
}
// validate at your will here.
return true;
}
checkSchema({
employees: {
isArray: {
bail:true,
options: {
min: 0,
},
},
custom: {
options: customValidator
},
},
"employees.*.roleId": {
isInt: true
},
"employees.*.employeeId": {
isInt: true
}
})
Run Code Online (Sandbox Code Playgroud)
let arr = [
{
user_id:1,
hours:8
},
{
user_id:2,
hours:7
}
]
Run Code Online (Sandbox Code Playgroud)
您可以像这样放置支票:
check("arr.*.user_id")
.not()
.isEmpty()
check("arr.*.hours")
.not()
.isEmpty()
Run Code Online (Sandbox Code Playgroud)
小智 5
您可以通过访问请求正文来实现此目的:
const { body } = require('express-validator')
body('*.*')
.notEmpty()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2448 次 |
| 最近记录: |