Only allow properties that are declared in JSON schema

前端 未结 3 949
栀梦
栀梦 2020-12-15 02:09

I am using json-schema and wanting to only allow properties that are declared in this file to pass validation. For instance if a user passes a \"name\" property in their jso

相关标签:
3条回答
  • 2020-12-15 02:51

    FYI - it looks like v5 of the standard will describe a "ban unknown properties" validation mode.

    So instead of making this requirement part of the format (which as Chris Pitman says in the comments, damages future extensibility), you can simply instruct your validator to flag unknown properties as errors. So, it's like a super-strict validation mode which is useful for dev.

    Some validators already support this (e.g. tv4):

    var result = tv4.validateMultiple(data, schema, checkRecursive, banUnknownProperties);
    

    With this tool, checkRecursive should be used if your data might have circular references, and banUnknownProperties will do exactly what you want, without having to use "additionalProperties":false.

    0 讨论(0)
  • 2020-12-15 02:53

    I believe what you need to do to achieve this is set additionalProperties to false. See the specification here

    0 讨论(0)
  • 2020-12-15 02:57

    Inside your definition provide:

    • all required fields inside "required": []
    • and set "additionalProperties": false

    DEMO:

    without "additionalProperties": false:

    with "additionalProperties": false:

    0 讨论(0)
提交回复
热议问题