Flask WTform validation on multiple fields
Asked Answered
L

1

10

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.

Lysias answered 2/9, 2018 at 5:23 Comment(0)
T
16

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
Trichroism answered 2/9, 2018 at 17:14 Comment(1)
Awesome thanks! I had to add self.name and self.address to the database query, otherwise, it worked perfectly!Lysias

© 2022 - 2024 — McMap. All rights reserved.