0

有没有办法验证一个字段的存在取决于另一个字段的长度的文档?我的尝试:

import cerberus

schema = {
    'field_2': {
        'type': 'integer',
        'dependencies': {
            'field_1': {'maxlength': 1}
        }
    },
    'field_1': {
        'type': 'list',
    }
}
v = cerberus.Validator(schema)
doc = {
    'field_1': [1, ],
    'field_2': 77
}
if not v.validate(doc):
    print(v.errors)
else:
    print(True)

输出:

{'field_2': ["depends on these values: {'field_1': {'maxlength': 1}}"]}

预期输出是True

4

2 回答 2

3

可以使用自定义规则来完成:

from typing import Optional, Any, Tuple

from cerberus import Validator


class ExtendedValidator(Validator):
    def _validate_with_length(self, with_length, field, _value):
        # type: (Tuple[str, int], str, Any) -> Optional[bool]
        """Validating in dependence of length of other field in document

        The rule's arguments are validated against this schema:
        {'type': 'list'}
        """
        key, length = with_length
        if key not in self.document:
            return False
        if len(self.document[key]) != length:
            self._error(field, "Length of %s must be %s" % (key, length))


schema = {
    'field_2': {
        'type': 'integer',
        'with_length': ('field_1', 1),
    },
    'field_1': {
        'type': 'list',
    }
}

docs = [{'field_1': [1, ], 'field_2': 77}, {'field_1': [1, 2], 'field_2': 77}]
v = ExtendedValidator(schema)
for doc in docs:
    if not v.validate(doc):
        print(v.errors)
    else:
        print(True)

输出:

True
{'field_2': ['Length of field_1 must be 1']}
于 2017-12-16T11:19:46.297 回答
0

说得通?移至定义'maxlength': 1field_1

schema = {
    'field_2': {
        'type': 'integer',
        'dependencies': 'field_1'
    },
    'field_1': {
        'type': 'list',
        'maxlength': 1
    }
}
于 2017-12-14T14:22:15.000 回答