问题
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