[英]JOI validation for a string with json as a value
i am trying to validate the string using the JOI package available in npm, i checked this documentation which has many useful string formats eg date, IP, base64 but i need to validate the following JSON which contains a stringified JSON as a value, and there is no example in the documentation for such case我正在尝试使用 npm 中可用的 JOI 包来验证字符串,我检查了这个文档,它有许多有用的字符串格式,例如日期、IP、base64,但我需要验证下面的 JSON,它包含一个字符串化的 JSON 作为值,并且有在这种情况的文档中没有示例
{
"id": 232,
"name": "Trojan Horse",
"file": "download.exe",
"infected": true,
"engines": "['Norton', 'AVG', 'NOD32']"
}
So for example what if i want to check engines
have valid JSON value and have at-least one engine defined if infected
key is set to true
例如,如果我想检查
engines
是否具有有效的 JSON 值,并且如果infected
的密钥设置为true
,则至少定义一个引擎怎么办?
The following schema works only if the engines
value is written as parsed JSON以下架构仅在
engines
值被编写为解析的 JSON 时才有效
Joi.object().keys({
id: Joi.number().required(),
name: Joi.string().min(5).required(),
file: Joi.string().min(3).required(),
infected: Joi.boolean().required(),
engines: Joi.array().when('infected', {
is: Joi.exists().valid(true),
then: Joi.min(1).required()
})
});
What you need to do is to create a custom JOI validator by extending the array validator of the JOI package and using that custom validator for the engines property.您需要做的是通过扩展 JOI 包的数组验证器并将该自定义验证器用于引擎属性来创建自定义 JOI 验证器。
const custom = Joi.extend({
type: 'array',
base: Joi.array(),
coerce: {
from: 'string',
method(value, helpers) {
if (typeof value !== 'string' ||
value[0] !== '[' && !/^\s*\[/.test(value)) {
return;
}
try {
return { value: JSON.parse(value) };
}
catch (ignoreErr) { }
}
}
});
const schema = Joi.object({
id: Joi.number().required(),
name: Joi.string().min(5).required(),
file: Joi.string().min(3).required(),
infected: Joi.boolean().required(),
engines: custom.array().when('infected', {
is: true,
then: custom.array().min(1).required()
})
})
const validateTest = async (joiSchema, testObject) => {
try {
const value = await joiSchema.validateAsync(testObject);
console.log(value);
}
catch (err) {
console.error(err)
}
};
validateTest(schema, {
"id": 232,
"name": "Trojan Horse",
"file": "download.exe",
"infected": true,
"engines": `["Norton", "AVG", "NOD32"]`
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.