Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use JSON Schema to require one of two fields

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"   ] } 
like image 696
Jolly Avatar asked Dec 25 '16 13:12

Jolly


People also ask

What is allOf in JSON Schema?

By the definition of this keyword, it meant that the instance had to be valid against the current schema and all schemas specified in extends ; basically, draft v4's allOf is draft v3's extends .

What is a JSON Subschema?

JSON Schema is a language for declaring the structure of valid JSON data. There are validators that can decide whether a specific JSON document is valid with respect to a schema.

How do you reference a JSON Schema in another JSON Schema?

A schema can reference another schema using the $ref keyword. The value of $ref is a URI-reference that is resolved against the schema's Base URI. When evaluating a $ref , an implementation uses the resolved identifier to retrieve the referenced schema and applies that schema to the instance.

How do I set a schema in JSON?

At the top of the file, you can specify the schema's id, the schema that should be used to validate the format of your schema, and a descriptive title. These are all defined using the keywords id, $schema and title, all of which are provided in the draft JSON Schema.


1 Answers

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.

like image 182
esp Avatar answered Sep 19 '22 20:09

esp