conditional content matching and partial string comparisons using json schema

Viewed 65

I have a case where I need to check the content of one field, based on a partial match (contains) of the content of another field, for validations.

In more specific....if field A contains the string "option 3", and its actually part of a much longer string "Routing Option 3, with user defined....." etc etc and so on... then I need to check field B to make certain that it contains "more than 1 entry in an array". If the first check fails, then I need to check and make sure it contains "Exactly 1 entry, and that entry needs to be an empty string"

Here are the requirements in pseudocode

If (property A contains "Option 3" [case invariant])
    Validate property B.Length >= 2
else
    Validate property B === [""]

Is this complexity of comparison even possible using raw jsonSchema?

1 Answers

You can express your constrain with if/then/else. The pattern would look something like this,

  "if": { "$ref": "#/$defs/is-option-3" },
  "then": { "$ref": "#/$defs/option-3-assertions" },
  "else": { "$ref": "#/$defs/not-option-3-assertions" },

The way these keywords work is that if the JSON instance passes validation against the if schema, then the it must also pass validation against the then schema. If if fails, then the instance must pass against the else schema.

The #/$defs/is-option-3 schema can use the pattern keyword to assert that property "A" contains "Option 3". You can use the minLength and maxLength keywords in the other two schemas to make assertions about the string length.

Related