我有一个问题。
"Formula": {
"Type": "Import/Export",
"Params": {
"ShippingSourceType": "System/Country/Group",
ShippingDestinationType:"System/Country/Group"
}
}
我有上面的对象,我必须在其中对类型进行验证。但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') })
但它没有起作用。你能建议一下如何解决这个问题吗?
原来这是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');
});