簡體   English   中英

使用when的簡單joi模式不起作用

[英]Simple joi schema using when does not work

我希望以下內容會顯示錯誤:

var joi = require('joi');

var schema = {
  role_type: joi.string(),
  info: {
    address: joi.object({
      postal_code: joi.string(),
      country: joi.string().uppercase().length(2)
    })
      .when('role_type', {
        is: 'org', // When role_type is "org" the address props become required
        then: {
          postal_code: joi.required(),
          country: joi.required()
        }
      })
  }
};

var data = {
  role_type: 'org',
  info: {address: {country: 'AF'}}
};

joi.assert(data, schema);

不幸的是,上面的代碼沒有產生錯誤。 為什么?

已在joi v6和最新的v10上測試。

原來一個不能引用父對象的數據:

引用不能指向對象樹,只能指向同級鍵,但是它們可以指向其同級的子級

最簡單的解決方法是將.when()向上移動一個級別,以便joi將(深度)合並兩個info子方案

var schema = {
  role_type: joi.string(),
  info: joi.object({
    address: joi.object({
      postal_code: joi.string(),
      country: joi.string().uppercase().length(2)
    })
  })
    .when('role_type', {
      is: 'org',
      then: joi.object({
        address: joi.object({
          postal_code: joi.required(),
          country: joi.required()
        })
      })
    })
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM