user2962885
user2962885

Reputation: 111

Json schema validating length of one field based on another field

I have a JSON Schema with two fields. fieldA and fieldB, fieldA is an enum, fieldB is a string. I want to add some validations on the length of fieldB based on the value of fieldA.

properties:
  fieldA:
    enum:
      - VAL1
      - VAL2
      - VAL3
  fieldB:
     type: string
      pattern: '^[<a-z>{10}|<a-z>{5}]$'

I want to verify that if fieldA is equal to VAL1 then length of fieldB should be 5 else the length of fieldB should be 10. How to add such validation checks?

Upvotes: 3

Views: 3617

Answers (1)

Helen
Helen

Reputation: 97847

The answer depends on whether you use OpenAPI 2.0 (swagger: '2.0') or OpenAPI 3.0 (openapi: 3.0.0).

OpenAPI 2.0

OpenAPI 2.0 does not support conditional dependencies. You can only document such dependencies verbally in the description.

OpenAPI 3.0

You can use oneOf to describe conditional dependencies in OpenAPI 3.0, similar to how you would do it in JSON Schema. The example below is based on the answers to JSON schema conditional dependency on value.

Note while oneOf is part of the OpenAPI Specification (as in, you can write API definitions that include oneOf), actual tooling support for oneOf may vary.

type: object
required:
  - fieldA
properties:
  fieldA:
    type: string
    enum:
      - VAL1
      - VAL2
      - VAL3
  fieldB:
    type: string
    pattern: '^[a-z]+$'
oneOf:
  # If fieldA = VAL1, then fieldB must be 5 chars long
  - properties:
      fieldA:
        enum: [VAL1]
      fieldB:
        minLength: 5
        maxLength: 5
  # Otherwise (if fieldA = VAL2 or VAL3) fieldB must be 10 chars long
  - properties:
      fieldA:
        enum: [VAL2, VAL3]
      fieldB:
        minLength: 10
        maxLength: 10

Upvotes: 5

Related Questions