简体   繁体   English

Ajv javascript 模式验证与键值中的正则表达式

[英]Ajv javascript schema validation with regex in key value

I have a schema to validate with Ajv in Node.js.我有一个架构可以在 Node.js 中使用 Ajv 进行验证。 There is a recurrent pattern on the properties of the json to convalidate, the possible keys value are 1,2,3,4,5. json 的属性有一个循环模式来验证,可能的键值是 1,2,3,4,5。 The question is, it's possible with a regex expression to express only one property that will explain to ajv that the keys value of the json object could be an integer between one and five?问题是,有可能使用正则表达式仅表达一个属性,该属性将向 ajv 解释 json object 的键值可能是 integer 介于 1 和 5 之间吗? And if so, how?如果是这样,怎么办?

Below there is an example of the current code.下面是当前代码的示例。

const Ajv = require("ajv")
const ajv = new Ajv()

const validate_setparameters = ajv.compile(
    {
        type: "object",
        properties: {
            "1": { type: "integer"},
            "2": { type: "integer"},
            "3": { type: "integer"},
            "4": { type: "integer"},
            "5": { type: "integer"}
        },
        additionalProperties: false,
        minProperties: 1
    }
)

console.log(validate_setparameters({"3":1}))

See it: https://ajv.js.org/json-schema.html#patternproperties看到它: https://ajv.js.org/json-schema.html#patternproperties

So your code will be looks like:因此,您的代码将如下所示:

const Ajv = require("ajv")
const ajv = new Ajv()

const validate_setparameters = ajv.compile(
    {
        type: "object",
        patternProperties: {
            "^[1-5]{1}$": { type: "integer"}
        },
        additionalProperties: false,
        minProperties: 1
    }
)

console.log(validate_setparameters({"3":1}))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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