在RadioField上的WTForms自定义验证器 - RequiredIf

时间:2018-06-11 21:25:43

标签: validation flask radio-button flask-wtforms wtforms

我借用了一个验证器,如果另一个字段的值是某个值,则要求用户输入数据:

class RequiredIf(object):
    def __init__(self, *args, **kwargs):
            self.conditions = kwargs
    def __call__(self, form, field):
            for name, data in self.conditions.items():
                if name not in form._fields:
                    Optional(form, field)
                else:
                    condition_field = form._fields.get(name)
                if condition_field.data == data and not field.data:
                    DataRequired()(form, field)
                    Optional()(form, field)

当包含validator参数的字段为TextField时,这非常有效,但当字段为RadioField时,它似乎无效。我如何调整验证器,以便这也适用于RadioFields?

就目前而言,无论验证条件是否适用,始终会为RadioField返回not a valid choice

提前致谢。

例如:

class new_form(Form):
    code=BooleanField('Do you code?')
    code2=RadioField('If so, what languages do you use?',
        choices=[('python','python'),('C++','C++')],
        validators=[RequiredIf(code=1)])

无论是否选中BooleanField code,都会为this is not a valid choice返回code2。我想要一个验证器,它需要输入任何类型的字段(包括RadioField),条件是另一个字段的值(在这种情况下为code=1)。

1 个答案:

答案 0 :(得分:1)

<强>已更新!即可。您可以使用__call__创建任何自定义处理。例如:

from multidict import CIMultiDict
from wtforms import Form, RadioField, BooleanField


class RequiredIf(object):

    def __init__(self, **kwargs):
        self.conditions = kwargs

    def __call__(self, form, field):
        # NOTE! you can create here any custom processing
        current_value = form.data.get(field.name)
        if current_value == 'None':
            for condition_field, reserved_value in self.conditions.items():
                dependent_value = form.data.get(condition_field)
                if condition_field not in form.data:
                    continue
                elif dependent_value == reserved_value:
                    # just an example of error
                    raise Exception(
                        'Invalid value of field "%s". Field is required when %s==%s' % (
                            field.name,
                            condition_field,
                            dependent_value
                        ))

class NewForm(Form):
    code = BooleanField('Do you code?')
    code2 = RadioField(
        'If so, what languages do you use?',
        choices=[('python', 'python'), ('C++', 'C++')],
        validators=[RequiredIf(code=True)])

form = NewForm(formdata=CIMultiDict(code=True, code2='python'), )
form.validate()  # valid data - without errors

# invalid data
form = NewForm(formdata=CIMultiDict(code=True), )
form.validate()  # invalid data - Exception: Invalid value of field "code2". Field is required when code==True

另外两个例子RadioField

class NewForm(Form):
    list_one = RadioField('City/Country', choices=['city', 'country'])
    list_two = RadioField(
        'Cities',
        choices=[('minsk', 'Minsk'), ('tbilisi', 'Tbilisi')],
        validators=[RequiredIf(list_one='city')])


form = NewForm(formdata=CIMultiDict(list_one='city', list_two='minsk'), )
form.validate()  # without errors
form = NewForm(formdata=CIMultiDict(list_one='country'), )
form.validate()  # without errors
form = NewForm(formdata=CIMultiDict(list_one='city'), )
form.validate()  # invalid data - Exception: Invalid value of field "list_two". Field is required when list_one==city

希望这有帮助。