2017-08-16 5 views
1

Cerberusは2つのフィールドの要素が同じであることを検証する方法はありますか?2つのパラメータがCerberusを使用して同じ量の要素を持っていることを確認する

例えば、この文書は検証します:

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

そして、これはしません:

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

は、これまでのところ、私はこのスキーマが出ている:

​​

しかし、 2つのフィールドの等しい長さをテストするルールはありません。 custom rule

答えて

2

それはかなり単純明快です:

>>> 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 
関連する問題