一、普通一层参数的校验方法是这样的:
const rule = {
goodsId: { type: 'number', required: true },
name: { type: 'string', required: false },
categoryId: { type: 'number', required: false },
unitName: { type: 'string', required: false },
salePrice: { type: 'number', required: false },
spec: { type: 'string', required: false },
thumbnail: { type: 'string', required: false },
imagesPic: { type: 'string', required: false },
goodsInfo: { type: 'string', required: false },
};
ctx.validate(rule, ctx.request.body);
注:validate()第二个参数不传,默认就是取的ctx.request.body。
二、如何进行嵌套的数组或对象校验呢?
我们查看egg-validator
源码,发现它其实是引用的parameter
这个框架。
网上分析源码的那个,答案是错误的。
其实,我们去查看parameter的README.md
文档其实就能够找到答案
所以,正确的方式是如下:
const rule = {
products: {
type: 'array',
itemType: 'object',
rule: {
goodsSN: { type: 'string', required: true }, // 商品规格名称
goodsId: { type: 'number', required: true },
goodsNumber: { type: 'number', required: true }, // 单价
},
},
};
ctx.validate(rule);
那么当我们输入错误的参数时,返回的提示信息如下:
{
"code": 500,
"message": "Validation Failed",
"detail": [
{
"message": "required",
"field": "products[0].goodsId",
"code": "missing_field"
},
{
"message": "required",
"field": "products[0].goodsNumber",
"code": "missing_field"
}
]
}
当然,返回接口是是处理过了的。大家查看错误提示信息就可以了。