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" ] }
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 .
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With