如何在JOI模式验证条件下访问数组外部的键

时间:2016-01-14 07:37:07

标签: javascript hapijs joi

我有一个问题。

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

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

如果ShippingSourceType是系统,则Type应为Export。 如果ShippingDestinationType是系统,则类型应为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') })

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

1 个答案:

答案 0 :(得分:0)

原来这是a bug with 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');
});