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