trailblazer / reform

Form objects decoupled from models.
https://trailblazer.to/2.1/docs/reform.html
MIT License
2.49k stars 184 forks source link

How to validate JSON object where keys are variable and unknown? #523

Closed contentfree closed 3 years ago

contentfree commented 3 years ago

Consider the following JSON object:

{
  "sources": {
    "source1": { "type": "a" },
    "source2": { "type": "b" },
    "another one": { "type": "a" }
  }
}

(This structure is useful to ensure unique source identifiers, as opposed to putting objects containing an ID property in an array.)

I'd like to use Reform to validate this such that all values in the sources map have a type property (and have either a or b).

How does one accomplish this with Reform?

konung commented 3 years ago

Yes, it's possible to validate deeply nested hashes.

2 ways:

  1. You can intelligently parse out incoming data, into a predefined simpler structure using a custom populator: http://trailblazer.to/2.1/docs/reform.html#reform-populators . Then validate simpler structure.
  2. If the keys are unknown, you just want to validate, then you can use a custom validator with internal logic, me thinks. http://trailblazer.to/2.1/docs/reform.html#reform-validation-validation-groups
contentfree commented 3 years ago

Interesting ideas, @konung. Thanks for the insight.

apotonick commented 3 years ago

Hi @contentfree, Hi @konung this is a feature I will allow in Reform 3 (codename "Transform").

How deeply nested is the data structure @contentfree ?