我有一个我尝试验证的唯一数据:
{
"name": "Some random name",
"blocks": [
{"cj5458hyl0001zss42td3waww": {
"quantity": 9,
"rate": 356.77,
"dId": "ewdwe4434"
}},
{"cj5458hyl0001zss42td3wawu": {
"quantity": 4,
"rate": 356.77,
"dId": "3434ewdwe4434"
}}]
}
以下是我现在的作文( 无效且不正确 ):
const subSchema = {
"type": ["string"],
"pattern": "/^c[^\s-]{8,}$/",
"properties": {
"quantity": {
"type": "integer"
},
"rate": {
"type": "integer"
},
"dId": {
"type": "string"
}
},
"required": ["quantity", "rate", "dId"]
};
const schema = {
"type": ["object"],
"properties": {
"name": {
"type": "string"
},
"blocks": {
"type": "array",
"items": subSchema,
"uniqueItems": true,
"minItems": 1
}
},
"required": ["name", "blocks"]
};
以及我如何验证它(对于上下文):
const { BadRequestError } = require("restify");
const ajv = require("ajv");
var schemaValidator = ajv();
const validateRoomTypePostRequest = (req, res, next) => {
if (req.body && req.body.data){
const blockReq = Object.assign({}, req.body.data);
const testSchemaValidator = schemaValidator.compile(schema);
const valid = testSchemaValidator(blockReq);
if (!valid) {
const messages = testSchemaValidator.errors.map(e => {
return e.message;
});
return next(new BadRequestError(JSON.stringify(messages)));
}
return next();
}
else {
return next(new BadRequestError("Invalid or non-existent request body"));
}
};
这是我到目前为止所引用的内容:
1)AJV schema validation for array of objects
2)https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md
3)https://spacetelescope.github.io/understanding-json-schema/reference/object.html
其他信息:
1)使用节点8.1.3
2) AJV 版本 5.2
我知道我需要使用一系列项来描述对象。但是,该对象包含一个唯一的cuid作为键,值包含一个对象。我想了解如何使用验证嵌套属性和cuid的模式来描述此数据。我欢迎有关如何最好地处理这些数据的反馈。感谢您的时间。
答案 0 :(得分:0)
我做了一些灵魂搜索,并意识到我所要做的就是利用{
"blockType": {
"additionalProperties": false,
"type": "object",
"properties": {
"name": {
"type": "string"
},
"blocks": {
"type": "array",
"items": {
"type": "object",
"patternProperties": {
"^[a-z][a-z0-9\\-]*$": {
"type": ["object"],
"properties": {
"rate": {
"type": ["integer"]
},
"quantity": {
"type": ["integer"]
},
"dId": {
"type": "string"
}
},
"additionalProperties": false,
"required": ["dId", "quantity", "rate"]
}
}
}
}
},
"required": ["name", "blocks"]
}
}
关键字,特定于字符串。
{{1}}
我可以改进正则表达式来验证cuid。