Thomas Morrison
Thomas Morrison

Reputation: 647

Flask WTform validation on multiple fields

What is the best way to validate a WTform based on two or more entries? I.e. in the form below I want to validate that a company with the provided name and address do not already exist in the database.

class CompanyForm(FlaskForm):
    name=StringField('Company Name', validators=[DataRequired()])
    address=StringField('Street Address', validators=[DataRequired()])

Something like this...

    def validate_name(self, name, address):
        company = Company.query.filter_by(name=name.data, address=address.data).first()
        if company is None:
            raise ValidationError('This company already exists in our database.')

I read through the documentation and similar questions on S.O. but I still can't quite figure it out.

Upvotes: 10

Views: 5752

Answers (1)

Attack68
Attack68

Reputation: 4767

Try something like this.. (an amended version of the snippet here)

class CompanyForm(FlaskForm):
    name = StringField('Company', [validators.DataRequired()])
    address = StringField('Street Address', [validators.DataRequired()])

    def validate(self):
        rv = FlaskForm.validate(self)
        if not rv:
            return False

        company = Company.query.filter_by(name=self.name.data, address=self.address.data).first()
        if company is not None:
            self.name.errors.append('Company already exists at that address')
            return False

        return True

Upvotes: 16

Related Questions