Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 984
Thomas Morrison Avatar asked Sep 02 '18 05:09

Thomas Morrison


1 Answers

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
like image 107
Attack68 Avatar answered Nov 11 '22 10:11

Attack68