AJV始终返回true [英] AJV always returns true

查看:86
本文介绍了AJV始终返回true的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么即使对象错误,validate函数也总是返回true?

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.

推荐答案

一个空模式要么是{},要么是其键都不属于JSON模式词汇表的对象.无论哪种方式,空模式总是会返回true:

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

在您的情况下,schema没有包含有效的架构.但是schema.query确实如此.将其传递给Ajv的compile方法,它将按预期工作.

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>

或者,您可以在架构中添加$id,并使用Ajv的getSchema方法获取验证功能.

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

这也可行:

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)

这篇关于AJV始终返回true的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆