如何使用formencode验证器验证多个字段中至少有一个字段存在?

2024-06-28 20:00:11 发布

您现在位置:Python中文网/ 问答频道 /正文

对于Python Formencode验证器,有一个链式验证器RequireIfMissing和RequireIfPresent,它们允许给定其他字段的状态是否存在的要求。它似乎只适用于单个字段,这意味着如果缺少一个字段,需要另一个字段,或者如果存在一个字段,则需要另一个字段。如何至少需要一个字段?在


Tags: 状态链式formencoderequireifpresentrequireifmissing
1条回答
网友
1楼 · 发布于 2024-06-28 20:00:11

下面的类:RequireLeasstone将获得一个字段列表,并且仅当至少有一个字段存在时才会通过,如底部的成功和失败所示。在

from formencode import Schema, validators, Invalid
from formencode.validators import FormValidator


class RequireAtLeastOne(FormValidator):
    choices = []
    __unpackargs__ = ('choices',)
    def _convert_to_python(self, value_dict, state):
        for each in self.choices:
            if value_dict.get(each) is not None:
                return value_dict
        raise Invalid('You must give a value for %s' % repr(self.choices), value_dict, state)


class ValidateThings(Schema):
    field1 = validators.String(if_missing=None)    
    field2 = validators.String(if_missing=None)
    field3 = validators.String(if_missing=None)
    chained_validators = [RequireAtLeastOne(['field1', 'field2', 'field3'])]


""" Success """        
params = ValidateThings().to_python({"field2": 12})
params = ValidateThings().to_python({"field2": 12, "field3": 126})
params = ValidateThings().to_python({"field1": "foo", "field2": 12, "field3": 126})

""" Failure """
params = ValidateThings().to_python({})

相关问题 更多 >