简体   繁体   中英

How to declare schema for at least one property is not null using JSON Schema?

const personData= {
  name: null,
  email: 'test@gmail.com'
}

const schema = {
  instance: personData,
  schema: {
    type: "object",
    anyOf: [
      { required: ["name", "email"] }
    ]
  }
}

I want a schema which will validate the object and from object any of the key value (name or email) where one of them must be not null.

It looks like you're confused between "undefined" and "null", which are distinctly different. (I've now edited your question in light of your comment on my answer.)

The required keyword makes sure that a key is "defined" in the applicable object. The value is irrelevant, and may be null .

If you want to define the TYPE of a property, you have to use the type keyword.

anyOf must be an array of schemas where at least one of them must be true.

You've defined one subschema in the anyOf , and as a result, it must be true as a whole, making both items in the required array, required.

You want to define multiple schemas under your anyOf , where one each schema defines that a property must be of a specific type ( null is a type).


{
  "type": "object",
  "required": ["name", "email"],
  "anyOf": [
    {
      "properties": {
        "name": {
          "type": "string"
        }
      }
    }, {
      "properties": {
        "email": {
          "type": "string"
        }
      }
    }
  ]
}

You can solve this by placing the 'required' property under the anyof list

{
  "type": "object",
  "anyOf": [
    {
      "required": ["name"],
      "properties": {
        "name": {
          "type": "string"
        }
      }
    }, {
      "required": ["email"],
      "properties": {
        "email": {
          "type": "string"
        }
      }
    }
  ]
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM