1

I'm validating documents with Cerberus that roughly look like this:

{"a_dict": {"field1": "test1",
            "field2": "test2",
            "field3": "test3"}}

Not all of the fields in the subdocument need to be present, but one should. So far my schema looks like this:

"a_dict": {"type": "dict",
           "schema": {"field1": {"type": "string",
                                 "required": False},
                      "field2": {"type": "string", 
                                 "required": False},
                      "field3": {"type": "string",
                                 "required": False}}}

How can I enforce that at least one of the fieldX is provided?

This question is derived fom this issue.

funky-future
  • 3,716
  • 1
  • 30
  • 43

1 Answers1

1

This does the trick:

string_field = {'type': 'string'}
schema = {'a_dict': {'type': 'dict',
                     'minlength': 1,
                     'allow_unknown': False,
                     'schema':
                         {f: string_field for f in ('field1', 'field2', 'field3')}
                     }}
  • The minlength rule ensures that there's at least one field in a_dict.
  • The allow_unknown rule makes sure no other fields than field<1…3> pass the validation.
  • The required rule is False by default.
funky-future
  • 3,716
  • 1
  • 30
  • 43