【发布时间】:2019-06-28 12:39:33
【问题描述】:
我想为populatedStrings 创建一个自定义Joi 类型,方法是使用.extend(..) 创建一个基于joi.string() 的类型:
- 修剪字符串
- 如果是
trimmed string === '',则将值更改为undefined,这样经过验证的输出将根本不包含密钥 - 覆盖
.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 是 .required() 并且未提供它也不会失败。
【问题讨论】:
标签: javascript hapijs joi