How do I validate wtforms fields against one another?

YPCrumble picture YPCrumble · Feb 16, 2014 · Viewed 10.7k times · Source

I have three identical SelectField inputs in a form, each with the same set of options. I can't use one multiple select.

I want to make sure that the user selects three different choices for these three fields.

In custom validation, it appears that you can only reference one field at a time, not compare the value of this field to others. How can I do that? Thanks!

Answer

FogleBird picture FogleBird · Feb 16, 2014

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