1

Is there a way to have Cerberus validate that two fields have the same amount of elements?

For instance, this document would validate:

{'a': [1, 2, 3], b: [4, 5, 6]}

And this won't:

{'a': [1, 2, 3], 'b': [7, 8]}

So far I have come up with this schema:

{'a': {'required':False, 'type'= 'list', 'dependencies':'b'},
 'b': {'required':False, 'type'= 'list', 'dependencies':'a'}}

But there's no rule to test the equal length of two fields.

funky-future
  • 3,716
  • 1
  • 30
  • 43
Wang Nick
  • 385
  • 1
  • 6
  • 17

1 Answers1

5

With a custom rule it is pretty straight-forward:

>>> from cerberus import Validator

>>> class MyValidator(Validator):
        def _validate_match_length(self, other, field, value):
            if other not in self.document:
                return False
            if len(value) != len(self.document[other]):
                self._error(field, 
                            "Length doesn't match field %s's length." % other)

>>> schema = {'a': {'type': 'list', 'required': True},
              'b': {'type': 'list', 'required': True, 'match_length': 'a'}}
>>> validator = MyValidator(schema)
>>> document = {'a': [1, 2, 3], 'b': [4, 5, 6]}
>>> validator(document)
True
>>> document = {'a': [1, 2, 3], 'b': [7, 8]}
>>> validator(document)
False
funky-future
  • 3,716
  • 1
  • 30
  • 43
  • UserWarning: No validation schema is defined for the arguments of rule Getting this error when defining custom rules – Abhisek Roy Apr 27 '20 at 06:58
  • @AbhisekRoy, this is not an error, it's a warning that is emitted when you don't define a set of rules to validate given constraints in the schema: https://docs.python-cerberus.org/en/stable/customize.html#custom-rules – funky-future Apr 27 '20 at 13:06
  • I don't fully understand the docs regarding this warning. How should the docstring look like in order to avoid the user warning? – Andi May 07 '20 at 07:31