gpt4 book ai didi

javascript - 使用填充字符串的自定义类型扩展 Joi

转载 作者:行者123 更新时间:2023-12-04 17:41:00 27 4
gpt4 key购买 nike

我想为 populatedString 创建自定义 Joi 类型,方法是使用 .extend(..) 创建一个基于 joi.string() 的类型 其中:

  • trim 字符串
  • 如果 trimmed string === '' 将值更改为 undefined,这样经过验证的输出将根本不包含 key
  • 覆盖 .required() 因此它作用于 trim 后的字符串并使用我自己的语言创建错误。当 .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.required() 并且未提供它也不会失败。

最佳答案

我设法解决了它:

    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 并让它在调用 required() 时设置选项 presence = required

关于javascript - 使用填充字符串的自定义类型扩展 Joi,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54521797/

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