donjuardo
donjuardo

Reputation: 27

Require two fields to have the same value in JSON Schema

I need two different fields in my JSON Schema to have the same value. The validation should fail whenever the two values are different. Is this possible using only JSON Schema?

Upvotes: 1

Views: 141

Answers (2)

keithwalsh
keithwalsh

Reputation: 881

If, and only if, your JSON validator supports the $data keyword then you can enforce that two fields match each other, regardless of what that value actually is.

{
  "type": "object",
  "properties": {
    "field1": { "type": "string" },
    "field2": { "type": "string" }
  },
  "required": [ "field1", "field2" ],
  "allOf": [
    {
      "properties": {
        "field1": { "const": { "$data": "1/field2"  } }
      }
    }
  ]
}

Upvotes: 0

Jeremy Fiel
Jeremy Fiel

Reputation: 3307

Sure, you can use const.

{
    "$schema": "https://json-schema.org/draft-2020-12/schema",
    "type": "object",
    "properties": {
        "one": {
            "const": "same_value"
        },
        "two": {
            "const": "same_value"
        }
    }
}

Upvotes: -1

Related Questions