json模式验证后,如何让joi输出所有带路径的错误?

时间:2019-04-29 15:11:31

标签: javascript node.js joi

考虑代码:

const Joi = require('joi');
const joiAssert = require('joi-assert');

let json = {
  "myObject": {
    "myNestedField": {
      "deepOne": "myValue"
    }
  },
  "myArray": [
    {"field": 1},
    {"field": 2},
    {"field": 3}
  ]
};

joiAssert(json, Joi.object().required().keys({
  myObject: Joi.object().required().keys({
    myNestedField: Joi.object().required().keys({
      deepOne: Joi.string().required().valid("valid")
    }),
    myArray: Joi.array().items(
      Joi.object().keys({
        field: Joi.number().required().valid(8)
      })
    )
  })
}));

它失败并显示:

AssertionError: object: "deepOne" must be one of [valid]
    at Object.<anonymous> (joi-assert.js:17:1)
    at Module._compile (internal/modules/cjs/loader.js:689:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
    at Module.load (internal/modules/cjs/loader.js:599:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
    at Function.Module._load (internal/modules/cjs/loader.js:530:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:742:12)
    at startup (internal/bootstrap/node.js:283:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:743:3)    

有没有办法做类似的事情?

myObject.myNestedField.deepOne -  must be one of [valid]
myArray does not contain value [8] 

例如输出所有带有相应路径的验证错误?

0 个答案:

没有答案