javascript - 使用填充字符串的自定义类型扩展 Joi
问题描述
我想为populatedString
s 创建一个自定义 Joi 类型,方法是使用.extend(..)
以下类型创建一个类型joi.string()
:
- 修剪字符串
- 将值更改为
undefined
if ,trimmed string === ''
因此经过验证的输出根本不包含密钥 - 覆盖
.required()
,因此它作用于修剪后的字符串并使用我自己的语言创建错误。当 .required() 在我的类型上设置时,这意味着它需要一个不仅包含空格或为空的字符串
到目前为止,我的尝试很接近:
const StandardJoi = require("joi");
const Joi = StandardJoi.extend(joi => ({
base: joi.string(),
name: "populatedString",
language: {
required: "needs to be a a string containing non whitespace characters"
},
pre(value, state, options) {
value = value.trim();
return value === "" ? undefined : value;
},
rules: [
{
name: "required",
validate(params, value, state, options) {
if (value === undefined) {
return this.createError(
"populatedString.required",
{ v: value },
state,
options
);
}
return value;
}
}
]
}));
它工作的例子
Joi.populatedString().validate(" x "); // $.value === 'x'
Joi.populatedString().validate(" "); // $.value === undefined
// $.error.details
//
// [ { message: '"value" needs to be a a string containing non whitespace characters',
// path: [],
// type: 'populatedString.required',
// context: { v: undefined, key: undefined, label: 'value' } } ]
Joi.populatedString()
.required()
.validate(" ");
// $.value
//
// { inObj1: 'o' }
Joi.object()
.keys({
inObj1: Joi.populatedString()
})
.validate({ inObj1: " o " });
但它不会失败(因为它应该)
// { error: null, value: {}, then: [λ: then], catch: [λ: catch] }
Joi.object()
.keys({
inObj2: Joi.populatedString(),
inObj3: Joi.populatedString().required()
})
.validate({ inObj2: " " });
即使inObj3
is.required()
和 not 提供它也不会失败。
解决方案
我设法解决了它:
const BaseJoi = require("joi");
const Joi = BaseJoi.extend(joi => ({
base: joi.string(),
name: "populatedString",
language: {
required: "needs to be a a string containing non whitespace characters"
},
pre(value, state, options) {
value = value.trim();
return value === "" ? undefined : value;
},
rules: [
{
name: "required",
setup(params) {
return this.options({ presence: "required" });
},
validate(params, value, state, options) {
if (value === undefined) {
return this.createError(
"populatedString.required",
{ v: value },
state,
options
);
}
return value;
}
}
]
}));
修复方法是添加setup
并让它presence = required
在required()
被调用时设置选项。
推荐阅读
- python - Odoo 13 中的页码
- javascript - Mongoose + GraphQL 无法填充模型
- xml - Eclipse 中 plugin.xml 文件的格式不起作用
- c# - 将 Web 项目 (ASP.NET Core 3) 设置为 IdentityServer 的客户端和 ApiResource
- php - 使用 Eval 函数时无法捕获异常
- python-3.x - 超集 keycloak 配置
- git - Azure Jenkins Pipeline:Azure Web App 发布阶段的错误包标头构建失败
- graphql - GraphQl API 选择特定值
- sql-server - 如何创建周计数器?
- console.log - 如何查看 console.log 消息