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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With