问题描述
我在 JOI 14 上,似乎找不到升级指南以升级到 17。我看到有人为 JOI 16 发布了类似的问题,但最后一次更新是 3 个月前。根据我在 How to add custom validator function in Joi? 中看到的内容,16 中似乎不需要 library(tidyr)
library(data.table)
dat %>%
pivot_longer(cols = everything(),names_to = c('.value','grp'),names_sep="(?<=[A-Za-z])(?=[0-9])") %>%
group_by(grp,Z) %>%
summarise(Average = mean(Gol),.groups = 'drop') %>%
mutate(rn = rowid(grp)) %>%
pivot_wider(names_from = grp,values_from = c(Z,Average),names_sep = "") %>%
select(-rn) %>%
na.omit
# A tibble: 3 x 8
# Z1 Z2 Z3 Z4 Average1 Average2 Average3 Average4
# <chr> <chr> <chr> <chr> <dbl> <dbl> <dbl> <dbl>
#1 Azam Goli Maz Carr 2 3.5 2 0.5
#2 Mith komi Moli Dad 2 4 1.5 0.5
#3 Moli Komi Sam Moli 3 2 2 0
。
我正在查看 https://joi.dev/api/?v=17.3.0#extensions,type
的描述是 type
。
我尝试过这样的事情:
The type of schema. Can be a string,or a regular expression that matches multiple types.
它给了我这个错误:
const snakeAlpha = joi => {
return {
type: 'object',name: 'snakeAlpha',base: joi.string().regex(/^[a-z]+(_[a-z]+)*$/)
};
};
const customJoi = Joi.extend({
type: 'object',rules: {
snakeAlpha
}
});
自从说 ValidationError: {
"type": "object","rules": {
"snakeAlpha" [1]: "[joi => {\n return {\n type: 'object',\n name: 'snakeAlpha',\n base: joi.string().regex(/^[a-z]+(_[a-z]+)*$/)\n };\n}]"
}
}
[1] "rules.snakeAlpha" must be of type object
后我就很困惑。我也尝试过 object
,因为这是基础,但它有相同的错误消息。
更新 我也意识到原来的例子只涵盖了一个不引用 joi (regex) 的简单规则。我也有引用其他自定义验证器的验证器,如下所示。解决这个案例也有奖励积分。
string
解决方法
Joi 扩展的文档对于这样一个有用的功能来说令人失望。幸运的是,Joi 的很多核心都是使用扩展编写的,因此可以从 the source 中学到很多东西。
如果我把你的规则写成一个扩展,它会是这样的:
const customJoi = Joi.extend(joi => ({
type: 'string',base: joi.string(),messages: {
'string.snakeAlpha': '{{#label}} must be snake case'
},rules: {
snakeAlpha: {
validate(value,helpers)
{
if (!/^[a-z]+(_[a-z]+)*$/.test(value))
{
return helpers.error('string.snakeAlpha',{ value });
}
return value;
}
}
}
}));
可以这样使用:
customJoi.object().keys({
foo: customJoi.string().snakeAlpha()
});
更新
这是否是处理依赖扩展的正确方式,我不确定,但这是我通常处理它们的方式......
我首先在一个数组中定义我的扩展,确保首先定义依赖扩展。然后我将重复使用之前的 customJoi
实例遍历数组,以便下一个扩展包含在它之前定义的那些。一个简单的工作示例可能比我用文字解释得更好!
(我还简化了扩展程序,使其更符合您的使用习惯)
const Joi = require('joi');
let customJoi = Joi;
const extensions = [
joi => ({
type: 'snakeAlpha',base: joi.string().regex(/^[a-z]+(_[a-z]+)*$/)
}),// this instance of 'joi' will include 'snakeAlpha'
joi => ({
type: 'kebabAlpha',base: joi.string().regex(/^[a-z]+(-[a-z]+)*$/)
}),// this instance of 'joi' will include 'snakeAlpha' and 'kebabAlpha'
joi => ({
type: 'arrayKebabAlpha',base: joi.array().items(joi.kebabAlpha())
})
];
extensions.forEach(extension =>
customJoi = customJoi.extend(extension));
customJoi.assert([ 'hello-world' ],customJoi.arrayKebabAlpha());