Ajv(Another JSON Schema Validator)是一个针对JSON Schema的快速校验器。它允许使用JSON Schema来定义数据模型和数据的格式。但是,在某些情况下,JSON Schema模式的静态定义可能无法满足我们的需求。这时,我们需要在模式中使用实际数据进行校验。
方法一:使用Ajv的define关键字
可以使用define关键字来定义一个schema,该schema可以引用外部数据来约束属性的定义。我们可以使用数据文件来定义一个schema,然后将其传递到定义函数中。例如:
// 定义schema const personSchema = { $id: 'http://example.com/person.schema.json', $schema: 'http://json-schema.org/draft-07/schema#', title: 'Person', type: 'object', properties: { firstName: { type: 'string' }, lastName: { type: 'string' }, age: { type: 'integer', minimum: 0 }, address: { type: 'object', properties: { street: { type: 'string' }, city: { type: 'string' }, state: { type: 'string' }, country: { type: 'string' }, }, required: ['street', 'city', 'state', 'country'], }, }, required: ['firstName', 'lastName', 'age', 'address'], };
// 使用define定义数据模型 const ajv = new Ajv(); ajv.addSchema(personSchema, 'person'); const validate = ajv.compile({ $ref: 'person#', additionalProperties: false, });
// 校验数据 const data = { firstName: 'John', lastName: 'Doe', age: 30, address: { street: '123 Main St', city: 'Anytown', state: 'CA', country: 'USA', zip: '12345', // 这个属性不在数据模型中 }, }; const valid = validate(data); console.log(valid
上一篇:AJV-如何验证相对引用