我有一个问题。
"Formula": {
"Type": "Import/Export",
"Params": {
"ShippingSourceType": "System/Country/Group",
ShippingDestinationType:"System/Country/Group"
}
}
我有上面的对象,我必须在Type上进行验证。但Type
取决于ShippingSourceType
和ShippingDestinationType
的参数。
如果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') })
但它没有用。你能建议如何解决这个问题吗?
答案 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');
});