1

我有一个问题。

"Formula": {
    "Type": "Import/Export",
    "Params": {
        "ShippingSourceType": "System/Country/Group",
        ShippingDestinationType:"System/Country/Group"
    }
}

我有上面的对象,我必须对 Type 进行验证。但是Type取决于ShippingSourceTypeShippingDestinationType在参数中。

如果ShippingSourceType是系统那么Type应该是Export。如果ShippingDestinationType是 System 那么 Type 应该是Import

我已验证类型如下:

Type: joi.alternatives().required()
    .when('Params.ShippingSourceType', { is: 'System', then: joi.string().valid('Export') })
    .when('Params.ShippingDestinationType', { is: 'System', then: joi.string().valid('Import') })

但它没有用。你能建议如何解决这个问题吗?

4

1 回答 1

0

原来这是Joi的一个错误

已推送提交以修复它,但将在版本 8 中发布。

同时,您可以通过从特定提交安装 Joi 来使用它,如下所示:

npm install --save git+https://github.com/hapijs/joi.git#5b60525b861a3ab99123cd8349cbd9f6ed50e262

然后,您可以使用:

var joi = require('joi');

var schema = joi.object({
  Formula: joi.object().keys({
    Type: joi.string() // Use joi.string()
      .when('Params.ShippingSourceType', { is: 'System', then: joi.string().valid('Export')})
      .when('Params.ShippingDestinationType', { is: 'System', then: joi.string().valid('Import')}),
    Params: joi.object(), // or additional validation
  }),
});

现在一切都按预期工作:

joi.validate({
  Formula: {
    Type: "Export",
    Params: {
      ShippingSourceType: "System",
      ShippingDestinationType:"Country"
    }
  }
}, schema, function (err, value) {
  // If I understood correctly, this should be valid
  console.log(err ? 'object invalid' : 'object valid');
});

joi.validate({
  Formula: {
    Type: "Import",
    Params: {
      ShippingSourceType: "System",
      ShippingDestinationType:"Country"
    }
  }
}, schema, function (err, value) {
  // If I understood correctly, this should be invalid since
  // ShippingSourceType == "System" => Type == "Export"
  console.log(err ? 'object invalid' : 'object valid');
});

joi.validate({
  Formula: {
    Type: "Import",
    Params: {
      ShippingSourceType: "Country",
      ShippingDestinationType:"System"
    }
  }
}, schema, function (err, value) {
  // If I understood correctly, this should be valid
  console.log(err ? 'object invalid' : 'object valid');
});

joi.validate({
  Formula: {
    Type: "Export",
    Params: {
      ShippingSourceType: "Country",
      ShippingDestinationType:"System"
    }
  }
}, schema, function (err, value) {
  // If I understood correctly, this should be invalid since
  // ShippingDestinationType == "System" => Type == "Export"
  console.log(err ? 'object invalid' : 'object valid');
});

joi.validate({
  Formula: {
    Type: "Export",
    Params: {
      ShippingSourceType: "Country",
      ShippingDestinationType:"Country"
    }
  }
}, schema, function (err, value) {
  // Should be valid
  console.log(err ? 'object invalid' : 'object valid');
});
于 2016-01-18T19:34:25.563 回答