繁体   English   中英

以 json 为值的字符串的 JOI 验证

[英]JOI validation for a string with json as a value

我正在尝试使用 npm 中可用的 JOI 包来验证字符串,我检查了这个文档,它有许多有用的字符串格式,例如日期、IP、base64,但我需要验证下面的 JSON,它包含一个字符串化的 JSON 作为值,并且有在这种情况的文档中没有示例

{
    "id": 232,
    "name": "Trojan Horse",
    "file": "download.exe",
    "infected": true, 
    "engines": "['Norton', 'AVG', 'NOD32']"
}

例如,如果我想检查engines是否具有有效的 JSON 值,并且如果infected的密钥设置为true ,则至少定义一个引擎怎么办?

以下架构仅在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()
    })
});

您需要做的是通过扩展 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM