[英]Simple joi schema using when does not work
我希望以下内容会显示错误:
var joi = require('joi');
var schema = {
role_type: joi.string(),
info: {
address: joi.object({
postal_code: joi.string(),
country: joi.string().uppercase().length(2)
})
.when('role_type', {
is: 'org', // When role_type is "org" the address props become required
then: {
postal_code: joi.required(),
country: joi.required()
}
})
}
};
var data = {
role_type: 'org',
info: {address: {country: 'AF'}}
};
joi.assert(data, schema);
不幸的是,上面的代码没有产生错误。 为什么?
已在joi v6和最新的v10上测试。
原来一个不能引用父对象的数据:
引用不能指向对象树,只能指向同级键,但是它们可以指向其同级的子级
最简单的解决方法是将.when()
向上移动一个级别,以便joi将(深度)合并两个info
子方案
var schema = {
role_type: joi.string(),
info: joi.object({
address: joi.object({
postal_code: joi.string(),
country: joi.string().uppercase().length(2)
})
})
.when('role_type', {
is: 'org',
then: joi.object({
address: joi.object({
postal_code: joi.required(),
country: joi.required()
})
})
})
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.