[英]Joi validate array of objects, such that only one object has specific property
I've been reading the Joi API doc for a while & though I suspect what I want to do is possible, I'm not seeing the solution. 我已经阅读Joi API文档已有一段时间了,尽管我怀疑自己想做的事情是可行的,但我没有看到解决方案。
Given the following, how can I validate that only one thing
has the special
property: 给定以下内容,我如何验证只有一
thing
具有special
属性:
let thing = {
name: Joi.string(),
special: Joi.boolean(),
}
let manyThings = {
things: Joi.array().items(thing),
}
If you're okay with having the first item in the array be the object that has the special
property, you can use array.ordered and define a second schema for the subsequent objects. 如果可以将数组中的第一项作为具有
special
属性的对象,则可以使用array.ordered并为后续对象定义第二个架构。
var joi = require('joi');
var thingSchmea = joi.object().keys({
name: joi.string().required(),
special: joi.boolean().required()
});
var thingWithoutSpecialSchema = joi.object().keys({
name: joi.string().required()
});
var manyThingsSchema = joi.array().ordered(thingSchmea.required()).items(thingWithoutSpecialSchema);
var t = [
{
name: 'cuthbert',
special: true
},
{
name: 'roland',
special: true
},
{
name: 'jake'
},
{
name: 'susan'
}
];
var result = joi.validate(t, manyThingsSchema);
console.log(JSON.stringify(result, null, 2));
The variable t
will fail validation because the second item in the array has a special
property. 变量
t
将使验证失败,因为数组中的第二项具有special
属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.