我已经看过Joi API,但是没有数组顺序之类的东西。我还研究了Joi refs
,但目前无法(如果我错了,请纠正我)在数组中使用它们。
我正在考虑使用extend
,但不确定是否可以检索整个数组。
输入:
const asc = [1,2,3];
const noOrder = [10,7,8];
const desc = [6,5,4];
所需的输出:
Joi.validate(asc, Joi.array().asc()) // True
Joi.validate(asc, Joi.array().desc()) // False
Joi.validate(desc, Joi.array().desc()) // False
Joi.validate(noOrder, Joi.array().desc()) // False
Joi.validate(noOrder, Joi.array().asc()) // True
所以我的问题是,我应该如何开始呢?任何想法都将不胜感激
答案 0 :(得分:1)
Joi没有提供任何内置方法来验证数组的顺序,因此您将必须extend
使用自己的扩展名,例如:
const Joi = require('joi');
const customJoi = Joi.extend((joi) => ({
base: joi.array(),
name: 'array',
language: {
asc: 'needs to be sorted in ascending order',
desc: 'needs to be sorted in descending order'
},
rules: [
{
name: 'asc',
validate(params, value, state, options) {
const isAscOrder = value.every((x, i) => i === 0 || x >= value[i - 1]);
return isAscOrder ? value : this.createError('array.asc', {v: value}, state, options);
}
},
{
name: 'desc',
validate(params, value, state, options) {
const isDescOrder = value.every((x, i) => i === 0 || x <= value[i - 1]);
return isDescOrder ? value : this.createError('array.desc', {v: value}, state, options);
}
}
]
}));
const ascSchema = customJoi.array().asc();
const descSchema = customJoi.array().desc();
// Validation results.
console.log(Joi.validate([5, 7, 9, 10], ascSchema)); //true
console.log('\n\n');
console.log(Joi.validate([5, 7, 6, 10], ascSchema)); //false
console.log('\n\n');
console.log(Joi.validate([5, 4, 2, 0], descSchema)); //true
console.log('\n\n');
console.log(Joi.validate([5, 4, 2, 6], descSchema)); //false
答案 1 :(得分:0)
As of v16.0.0,Joi支持使用以下架构验证数组的顺序:
Joi.array()
.items(Joi.number())
.sort({ order: 'ascending' });