egg-validate 基於 parameter,
但是在兩個官網上的對於引用類型並沒有做詳細說明,也,沒有例子。怎么驗證對象和數組呢?
只能扒開源碼來看了,如圖。
- 在源碼的上方,就有了一堆類型,一眼就看到了
checkObject和checkArray,點進去看看。。

2.這個方法,啥都沒做,就typeof了一下,去看看validate方法,但是這里有個判斷,rule.rule先留着

3.這個方法,先掃了一下。看到for...in 基本已經穩了,rules 是傳進來的參數。然后一下就明白了。可以進行嵌套寫法

一個例子:
驗證
const errors = ctx.validate({
data: {
type: 'object',
rule: {
name: 'string',
portrait_url: { type: 'string', allowEmpty: true},
carousel_url: { type: 'string', allowEmpty: true},
birthTime: 'int',
summary: { type: 'string', allowEmpty: false},
desc: { type: 'string', allowEmpty: true}
}
}
}, {data: ctx.request.body});
數據:
{
"name": "sss",
"portrait_url": "",
"carousel_url": "",
"birthTime": 123123123123,
"summary": "xxxx的主題",
"desc": "酸奶代奧術大師大所大所大所多"
}
數組
數組的話需要 itemType 屬性,然后就進行嵌套了
ctx.validate({
data: {
type: 'array',
itemType: {
type: 'object',
rule: {
title: { type: 'string', allowEmpty: false },
desc: { type: 'string', allowEmpty: false },
icon: { type: 'string', allowEmpty: false },
}
}
}
}, { data: data });

