簡體   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