1
有沒有辦法讓Cerberus驗證兩個字段具有相同數量的元素?使用Cerberus驗證這兩個參數具有相同數量的元素
例如,該文件將驗證:
{'a': [1, 2, 3], b: [4, 5, 6]}
,這將不會:
{'a': [1, 2, 3], 'b': [7, 8]}
到目前爲止,我想出了這個模式:
但沒有規則測試兩個領域的等長。
有沒有辦法讓Cerberus驗證兩個字段具有相同數量的元素?使用Cerberus驗證這兩個參數具有相同數量的元素
例如,該文件將驗證:
{'a': [1, 2, 3], b: [4, 5, 6]}
,這將不會:
{'a': [1, 2, 3], 'b': [7, 8]}
到目前爲止,我想出了這個模式:
但沒有規則測試兩個領域的等長。
隨着custom rule這是很直接:
>>> 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