Conditional Validation

Congratulations! You have made so far. We will learn about conditional validation in module

What is Conditional Validation?

Conditional validation involves applying validation rules based on the presence or absence of other properties in the JSON document.

For Example:

  • dependentRequired: if a property A is present, then property B must be present.

  • dependentSchemas: if a property A is present, then apply a sub-schema B.

  • if-then-else: if a sub-schema A is valid then sub-schema B must be valid, else sub-schema C must be valid.

  • implications: if sub-schema A is valid then sub-schema B must be valid.

we will see each of these in detail in the upcoming lessons.

dependentRequired

Consider a scenario where you have a JSON document with two properties name and age. You want to make sure that if the name property is present, then the age property must also be present.

1{
2  "name": "John",
3  "age": 25
4}

Schema

To achieve this, you can use the dependentRequired keyword in JSON Schema. The dependentRequired keyword allows you to specify that a property is required if another property is present.

1{
2  "type": "object",
3  "properties": {...},
4  "dependentRequired": {
5    "name": ["age"]
6  }
7}

In the above schema, we specify that if the name property is present, then the age property must also be present.

The value of the dependentRequired keyword is an object. Each entry in the object maps from the name of a property, p, to an array of strings listing properties that are required if p is present.

Task

1{
2  "name": "John Doe",
3  "creditCardNumber":"1234 5678 1234 5678",
4  "address":"123 Main St",
5}

You are given a Schema for the above JSON document in the side editor. Update the schema to make sure that if the creditCardNumber property is present, then the address property must also be present.

Loading...
Output
Please click the button or use
Shift+Enter
to view the output