10

I have two fields in my schema - one is a required property called "name" and the other is optional (used to define a sorting property) called "nameSort" and I want to express

If the "nameSort" field is defined, the "name" field should also be defined as the same value.

Is it possible to express such an "inter-element" constraint with JSON schema? My cursory read of JSON Schema here http://json-schema.org/latest/json-schema-validation.html says no.

kellyfj
  • 6,586
  • 12
  • 45
  • 66

2 Answers2

10

Old question, but this can now be done with json schema v5/v6 using a combination of the constant and $data (JSON pointer or relative JSON pointer) keywords.

Example:

"properties": {
    "password": { "type": "string" },
    "password_confirmation": { "const": { "$data": "1/password" } }
}

Where "1/password" is a relative JSON pointer saying "go up one level, then look up the key password".

Andrew
  • 1,431
  • 2
  • 16
  • 18
  • 4
    JSON schema does _not_ support `$data` as of draft 07, although validators like AJV does. See https://github.com/json-schema-org/json-schema-spec/issues/51 for details. – neverendingqs Mar 27 '18 at 19:38
  • 4
    As above, this is a non standard keyword and will NOT be interoperable between implementations. – Relequestual Aug 14 '18 at 08:13
6

You can express one property must be defined when another is present, e.g.:

{
    "type": "object",
    "dependencies": {
        "nameSort": ["name"]
    }
}

However, you cannot specify that two properties must have equal values.

Also, why do you have a separate property at all, if it's always going to be equal? And if it's always equal, could you just have a boolean flag to reduce redundancy?

cloudfeet
  • 12,156
  • 1
  • 56
  • 57
  • Thanks for that tip - that will help! Yes this is legacy code and some poor design decisions were made that are already in production with customers :-( – kellyfj Jan 12 '15 at 18:20
  • What is that what is that? Did you forget that you could just `"dependencies": { "p1": "p2" }`? :p @kellyfj this will work as to _require_ the property; however, if you want both to have the same VALUE, you'll have to have a custom keyword if you can afford it. Now, it depends on the validation library you use... – fge Jan 12 '15 at 21:50
  • Oops - yeah, I drafted more complicated constraints then forgot about it! Fixed - thanks. :) – cloudfeet Jan 13 '15 at 13:26
  • 4
    A use case for comparing equality of values would be a `password` and `password-repeat` pair. So, is that possible? – Joshua Kifer Dec 25 '15 at 20:25
  • I see that this proposal https://github.com/json-schema/json-schema/wiki/$data-(v5-proposal) can provide the means for this. This project supports it https://github.com/acornejo/jjv – Joshua Kifer Dec 25 '15 at 20:31