ajv
- ajv:https://ajv.js.org/
- json-schema: https://json-schema.org/
const Ajv = require("ajv")
const ajv = new Ajv() // options can be passed, e.g. {allErrors: true}
const schema = {
type: "object",
properties: {
foo: { type: "integer" },
bar: { type: "string" }
},
required: ["foo"],
additionalProperties: false
}
const validate = ajv.compile(schema)
const data = {
foo: "1",
bar: "abc"
}
const valid = validate(data)
if (!valid) console.log(validate.errors)
// 如果错了
[
{
instancePath: '/foo',
schemaPath: '#/properties/foo/type',
keyword: 'type',
params: { type: 'integer' },
message: 'must be integer'
}
]
format
https://ajv.js.org/guide/formats.html
String formats
还可以自定义
ajv.addFormat("byte", {
type: "number",
validate: (x) => x >= 0 && x <= 255 && x % 1 == 0,
})
keyword
ajv.addKeyWord("test", {
validate: (schema,data) { //schema是关键字的值,data是关键字所在的key
if(schema === true) return true
else return schema.length === 6
}
})