gpt4 book ai didi

javascript - Joi 验证数组的顺序

转载 作者:行者123 更新时间:2023-11-30 19:38:41 28 4
gpt4 key购买 nike

我查看了 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

所以我的问题是,我该如何开始呢?非常感谢任何想法

最佳答案

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

关于javascript - Joi 验证数组的顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55661562/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com