首页 > 解决方案 > 在前端有效地验证嵌套的 JSON 模式/配置

问题描述

我在一个typescript项目中有以下 JSON 配置。我想在运行时在前端验证这一点。我正在寻找类似的解决方案node-convict

我需要验证

  1. 唯一id/无重复 ID。
  2. 唯一的名称。
  3. 必填属性非空type
  4. 有条件的多个子类型,例如如果 type ===folder他们应该有children道具。它可以是一个空数组。
  5. 多个级别的嵌套对象。

我找到了AJV。AJV 文档仅指整个对象是唯一的,而不是特定的属性。我可能会想出自己的方法并进行一些递归验证。但是,我正在寻找最有效的解决方案,无论是使用 ajv、另一个库还是可以用来验证这一点的有效数据结构。

如果使用外部库,它需要与 typescript 兼容。我不是在寻找打字稿编译时验证。

[{
    "type": "folder",
    "name": "",
    "id": 1, // UUID
    "chldren": [{
            "id": 11, // UUID
            "type": "table", // TABLE TYPE
            "name": "Some Table 1",
            "meta": {},
            "dataSource": "..........."
        },
        {
            "type": "folder", // FOLDER TYPE
            "name": "",
            "id": 111, // UUID
            "chldren": [{
                "type": "folder",
                "name": "",
                "id": 1111, // UUID
                "chldren": [{
                    "id": 11111, // UUID
                    "type": "table",
                    "name": "Some Another Table",
                    "meta": {},
                    "dataSource": "..........."
                }]
            }]
        }
    ]
}]

标签: javascripttypescriptvalidationdata-structuresajv

解决方案


I'd recommend using the Joi data validation library. It has had browser support since version 16.

An example is as follows e.g.

import Joi from '@hapi/joi';

const schema = Joi.object({
    type: Joi.string()
        .alphanum()
        .required(),

    id: Joi.number()
        .integer()

    // I've not defined the whole schema for your object...
})     

You can then validate your object using:

schema.validate({ type: 'folder', id: 1 });
// -> { error: null, value: { type: 'folder', id: 1 }}

Or:

try {
    const value = await schema.validateAsync({ type: 'folder', id: 1 });
}
catch (err) { }

You can get the TypeScript typings for Joi from here.

An example of this working can be found here.


推荐阅读