这是我的架构:
const InvoiceSchema = new Schema({
name: { type: String, required: true },
description: { type: String },
items: [{
name: { type: String, required: true },
rate: { type: Number, required: true },
quantity: { type: Number, required:true, default: 1 },
amount: { type: Number }
}]});
我想知道如何使用Express-validator检查项目元素?
答案 0 :(得分:0)
之前遇到过同样的问题而且非常痛苦,特别是如果它需要深层数组或对象数组来验证。我最终创建了自己的验证器(wallter)来处理这个问题。此工具还可以直接从您的猫鼬模型生成验证模式。
因此,上面的架构将生成验证架构:
{
"name": {
"required": {
"msg": "Value for field 'name' is required"
}
},
"description": {
"optional": true
},
"items.*.name": {
"required": {
"msg": "Value for field 'items.*.name' is required"
}
},
"items.*.rate": {
"required": {
"msg": "Value for field 'items.*.rate' is required"
},
"isDecimal": {
"msg": "Expecting 'decimal' value for field 'items.*.rate'"
}
},
"items.*.quantity": {
"required": {
"msg": "Value for field 'items.*.quantity' is required"
},
"isDecimal": {
"msg": "Expecting 'decimal' value for field 'items.*.quantity'"
}
},
"items.*.amount": {
"optional": true,
"isDecimal": {
"msg": "Expecting 'decimal' value for field 'items.*.amount'"
}
}
}
此验证架构可以提供给验证器
const halter = require('wallter').halter
const Builder = require('wallter').builder // validation schema builder
const builder = new Builder({
model: mongoose.model('YourModelName')
})
server.use(halter())
server.post('/test', function (req, res, next) {
let validationSchema = builder.build() // see above generated validation schema output
req.halt(validationSchema).then(result => {
if (result.length) {
res.send(400, result)
} else {
res.send(200)
}
return next()
})
})