javascript - 在前端有效地验证嵌套的 JSON 模式/配置
问题描述
我在一个typescript
项目中有以下 JSON 配置。我想在运行时在前端验证这一点。我正在寻找类似的解决方案node-convict
。
我需要验证
- 唯一
id
/无重复 ID。 - 唯一的名称。
- 必填属性非空
type
- 有条件的多个子类型,例如如果 type ===
folder
他们应该有children
道具。它可以是一个空数组。 - 多个级别的嵌套对象。
我找到了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": "..........."
}]
}]
}
]
}]
解决方案
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.
推荐阅读
- javascript - 无法读取类中未定义的属性
- javascript - 来自 Spring RestController 的 jQuery.get
- python - Python for循环遍历数组创建JSON文件
- android - 在使用带有动作 ACTION_GET_CONTENT 的意图时传递带有意图的附加内容
- tslint - tslint 如何禁用错误“someVariable 已声明但其值从未被读取”
- java - iText 7:表的看似不可预测的行为
- python - 如何使用 map 和 reduce 在 Python 中按步骤组成函数列表
- c++ - QT 资源不起作用
- xml - 批量插入的行分隔符问题
- haskell - haskell中的变量赋值