AJV始终返回true

时间:2019-08-22 18:14:42

标签: javascript jsonschema ajv

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

Sub Sales_Report()

'For Tips see: http://www.rondebruin.nl/win/winmail/Outlook/tips.htm
'Don't forget to copy the function RangetoHTML in the module.
'Working in Excel 2000-2016
    Dim rng As Range
    Dim OutApp As Object
    Dim OutMail As Object

    Set rng = Nothing
    On Error Resume Next
    'Only the visible cells in the selection
    Set rng = Selection.SpecialCells(xlCellTypeVisible)
    'You can also use a fixed range if you want
    'Set rng = Sheets("YourSheet").Range("D4:D12").SpecialCells(xlCellTypeVisible)
    On Error GoTo 0

    If rng Is Nothing Then
        MsgBox "The selection is not a range or the sheet is protected" & _
               vbNewLine & "please correct and try again.", vbOKOnly
        Exit Sub
    End If

    With Application
        .EnableEvents = False
        .ScreenUpdating = False
    End With

    Set OutApp = CreateObject("Outlook.Application")
    Set OutMail = OutApp.CreateItem(0)

    On Error Resume Next
    With OutMail
        .To = ""
        .CC = ""
        .BCC = ""
        **.Subject = "X" & Date - 7 & Date - 1**
        .HTMLBody = RangetoHTML(rng)
        .Display
    End With
    On Error GoTo 0

    With Application
        .EnableEvents = True
        .ScreenUpdating = True
    End With

    Set OutMail = Nothing
    Set OutApp = Nothing
End Sub

我的代码有什么问题?这是一个基本示例。

1 个答案:

答案 0 :(得分:1)

一个空的模式要么是{},要么是其键都不属于JSON Schema词汇表的对象。无论哪种方式,空模式总是会返回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方法,它将按预期工作。

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方法获取验证功能。

这也可行:

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)