How do I validate wtforms fields against one another?

做~自己de王妃 提交于 2019-11-30 17:19:41

You can override validate in your Form...

class MyForm(Form):
    select1 = SelectField('Select 1', ...)
    select2 = SelectField('Select 2', ...)
    select3 = SelectField('Select 3', ...)
    def validate(self):
        if not Form.validate(self):
            return False
        result = True
        seen = set()
        for field in [self.select1, self.select2, self.select3]:
            if field.data in seen:
                field.errors.append('Please select three distinct choices.')
                result = False
            else:
                seen.add(field.data)
        return result

I wrote a small python library required to make cross-field validation like this easier. You can encode your validation logic declaratively as pairwise dependencies. So your form may look like:

from required import R, Requires, RequirementError

class MyForm(Form):

    VALIDATION = (
        Requires("select1", R("select1") != R("select2") +
        Requires("select2", R("select2") != R("select3") +
        Requires("select3", R("select3") != R("select1")
    )

    select1 = SelectField('Select 1', ...)
    select2 = SelectField('Select 2', ...)
    select3 = SelectField('Select 3', ...)

    def validate(self):
        data = {
            "select1": self.select1.data,
            "select2": self.select2.data,
            "select3": self.select3.data,
        }

        # you can catch the RequirementError
        # and append the error message to 
        # the form errors

        self.VALIDATION.validate(data)
        return result

You can take the VALIDATION object and append more validation rules or even put it in a separate module and import / reuse validation rules in different places.

Use FieldList like this:

def field_level(form, field):
    all_values = form.selects.data
    value = field.data

def list_level(form, field):
    all_values = field.data

class MyForm(Form):
    selects = FieldList(SelectField('label', validators=[field_level]), validators=[list_level])

form = MyForm()
form.append_entry()
form.append_entry()
form.append_entry()

You can have validators on Field level AND on FieldList level

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!