30
votes

I want to validate JSON to make one of two fields manadatory.

Let's assume we have two fields (Email Address and Phone Number). I want to make sure that one of the two fields is required for the record to be valid.

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "id": "ExampleID-0212",
  "title": "objectExamples",
  "description": "Demo",
  "type": "object",
  "properties": {
    "RecordObject": {
      "type": "object",
      "properties": {
        "emailAddress": {
          "type": "string"
        },
        "PhoneNumber": {
          "type": "number"
        }
      }
    }
  },
  "required": [
    "RecordObject"
  ]
}
2

2 Answers

39
votes

You need to add:

"anyOf": [
  { "required":
    [ "emailAddress" ] },
  { "required":
    [ "PhoneNumber" ] }
]

to the schema of RecordObject property.

It requires that at least one of fields is present. If you need exactly one field (i.e., not both) present, you need to use "oneOf" keyword (the rest should be the same).

This reference of JSON Schema keywords can be useful.

-11
votes

Sooperb Answer from ESP.. that is from jsonSchema ...

you can also do that validation thorugh condition..see below

 if(EmailAddress == null && PhoneNumber == null){
     //statements or error message response
}