有没有办法拥有Cerberus验证两个字段是否具有相同数量的元素?
例如,该文档将验证:
{'a': [1, 2, 3], b: [4, 5, 6]}
这不会:
{'a': [1, 2, 3], 'b': [7, 8]}
到目前为止,我已经想出了这个模式:
{'a': {'required':False, 'type'= 'list', 'dependencies':'b'},
'b': {'required':False, 'type'= 'list', 'dependencies':'a'}}
但没有规则可以测试两个字段的长度是否相等。
With a 自定义规则这非常简单:
>>> 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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)