4

我有一个这样的嵌套模式设置:

var schema = Joi.object().keys({
  first_name: Joi.string().required(),
  last_name: Joi.string().required(),
  address: Joi.object().keys({
    street: Joi.string().required(),
    zip: Joi.number().required(),
    state: Joi.string().required(),
    country: Joi.string().required()
  }).required(),
})

var options = { abortEarly: false };

var result = Joi.validate({}, schema, options);

运行时,result.error将返回消息:

[
  {message: '"first_name" is required', path: 'first_name' }, 
  {message: '"last_name" is required', path: 'last_name' },
  {message: '"address" is required', path: 'address' }
]

如您所见,该address字段未扩展。我不想收到缺少整个地址字段的消息。相反,我想了解地址架构中缺少的各个项目。当我没有address明确要求时,其中的项目根本不会得到验证required()。嵌套字段验证似乎仅适用于整个嵌套模式对象级别,而不适用于模式级别中的单个项目。如何使其与单个嵌套模式项一起使用?

4

1 回答 1

1

添加“骨架”对象有效。这里的工作示例。

import Joi, {
  string,
  number,
  object
} from "joi";

var schema = object({
  first_name: string().required(),
  last_name: string().required(),
  address: object({
    street: string().required(),
    zip: number().required(),
    state: string().required(),
    country: string().required()
  })/*.required(), <= Not needed */
})
var skeleton = { address: {} };

var options = { abortEarly: false };

var validate = data => {
  var newData = Object.assign({}, skeleton, data);
  return Joi.validate( newData, schema, options);
}
console.log(
  JSON.stringify(validate({}).error.details, null, 2)
);

结果:

[
  {
    "message": "\"first_name\" is required",
    "path": "first_name",
    "type": "any.required",
    "context": {
      "key": "first_name"
    }
  },
  {
    "message": "\"last_name\" is required",
    "path": "last_name",
    "type": "any.required",
    "context": {
      "key": "last_name"
    }
  },
  {
    "message": "\"street\" is required",
    "path": "address.street",
    "type": "any.required",
    "context": {
      "key": "street"
    }
  },
  {
    "message": "\"zip\" is required",
    "path": "address.zip",
    "type": "any.required",
    "context": {
      "key": "zip"
    }
  },
  {
    "message": "\"state\" is required",
    "path": "address.state",
    "type": "any.required",
    "context": {
      "key": "state"
    }
  },
  {
    "message": "\"country\" is required",
    "path": "address.country",
    "type": "any.required",
    "context": {
      "key": "country"
    }
  }
]
于 2017-06-01T21:53:41.617 回答