我们已经使用了相当多的字段级别的验证,它非常棒而且功能强大。但是,有时文档本身只有在评估多个字段时才有效。更改涉及的任何字段都必须触发验证。
我们现在所做的是将验证应用到涉及到的每个字段-在POST上多次运行验证。
有没有办法将验证规则应用于文档本身?
例如,假设some_thing有两个字段,验证会考虑这两个字段。如果其中任何一个发生更改,我们必须针对另一个进行验证。
这行得通..。
验证器(为清晰起见简化):
def _validate_custom_validation(self, custom_validation, field, value):
if field == "field1":
f1 = value
f2 = self.document.get('field2')
if field == "field2":
f1 = self.document.get('field1')
f2 = value
if custom_validation and not is_validate(f1, f2):
self._error(field, "validation failed...")然后是模式定义:
DOMAIN = {
some_thing: {
schema: {
field1: {
'type': 'string',
'custom_validation': True
},
field1: {
'type': 'string',
'custom_validation': True
}
}
}
}但是我们想做这样的事情:
验证器
def _validate_custom_validation(self, custom_validation):
f1 = self.document.get('field1')
f2 = self.document.get('field2')
if custom_validation and not is_validate(f1, f2):
self._error(resource, "validation failed...")然后是模式定义:
DOMAIN = {
some_thing: {
'custom_validation': True,
schema: {
field1: {
'type': 'string'
},
field1: {
'type': 'string'
}
}
}
}这个是可能的吗?
发布于 2018-10-15 16:16:37
您可以覆盖main验证方法,使其首先检查标准规则,然后检查模式级规则:
class validator_decorator(Validator):
def validate(self, document, schema=None, update=False, normalize=True):
super(validator_decorator, self).validate(document, schema=schema, update=update, normalize=normalize)
def validate_schema_rule(rule, document):
validator = self.__get_rule_handler('validate', rule)
validator(self.schema, document)
schema_rules = app.config['DOMAIN'][self.resource].get('validation')
if schema_rules:
for rule in schema_rules:
validate_schema_rule(rule, document)
return not bool(self._errors)此验证器允许您执行以下操作
'users': {
'validation': ['validator_name'],
'schema': ...
}当然,您还需要实现validator_name,与documantation says - in validator_decorator类的实现方式相同
https://stackoverflow.com/questions/48341015
复制相似问题