AJV always returns true

徘徊边缘 提交于 2021-01-29 18:00:21

问题


Why does the validate function always return true even if the object is wrong?

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

const schema = {
    query: {
        type: 'object',
        required: ['locale'],
        properties: {
            locale: {
                type: 'string',
                minLength: 1,
            },
        },
    },
}

const test = {
    a: 1,
}

const validate = ajv.compile(schema)
const valid = validate(test)
console.log(valid) // TRUE

What is wrong with my code? It is a basic example.


回答1:


An empty schema is either {} or an object which none of its keys belong to the JSON Schema vocabulary. Either way an empty schema always return true:

const ajv = new Ajv();

const validate1 = ajv.compile({});
const validate2 = ajv.compile({
  "a": "aaa",
  "b": [1, 2, 3],
  "c": {
    "d": {
      "e": true
    }
  }
});

validate1(42); // true
validate1([42]); // true
validate1('42'); // true
validate1({answer: 42}); // true

validate2(42); // true
validate2([42]); // true
validate2('42'); // true
validate2({answer: 42}); // true

In your case schema does not contain a valid schema. However schema.query does. Pass that to Ajv's compile method and it will work as expected.

const ajv = new Ajv()

const schema = {
    query: {
        type: 'object',
        required: ['locale'],
        properties: {
            locale: {
                type: 'string',
                minLength: 1,
            },
        },
    },
}

const test = {
    a: 1,
}

const validate = ajv.compile(schema.query)
const valid = validate(test)
console.log(valid)
<script src="https://cdnjs.cloudflare.com/ajax/libs/ajv/6.10.2/ajv.min.js"></script>

Alternatively, you could add an $id to your schema and get a validation function with Ajv's getSchema method instead.

This works too:

const schema = {
    query: {
        $id: 'query-schema',
        type: 'object',
        required: ['locale'],
        properties: {
            locale: {
                type: 'string',
                minLength: 1,
            },
        },
    },
}

const test = {
    a: 1,
}

ajv.addSchema(schema)

const validate = ajv.getSchema('query-schema')
const valid = validate(test)
console.log(valid)


来源:https://stackoverflow.com/questions/57615009/ajv-always-returns-true

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!