wtforms raise a validation error after the form is validated

痞子三分冷 提交于 2019-12-05 03:31:29

I solved it by manually appending errors to the field i wanted.

It looks like that

try:

    [...]
except StripeError as e:
    form.payment.errors.append('the error message')
else:
    db.session.commit()
    return redirect(url_for('home'))

on your wtform itself you can add a method prefixed with validate_ in order to raise an exception.

class RegistrationForm(Form):
  amount = IntegerField('amount', validators=[Required()])

  validate_unique_name(self, field):
    if field.data > 10000:
      raise ValidationError('too much money')

in my case I used it like so to validate that a user was not in the database already:

class Registration(Form):
  email = StringField('Email', validators=[Required(), Email()]) # field for email
  # ...
  def validate_email(self, field): # here is where the magic is
    if User.query.filter_by(email=field.data).first(): # check if in database
      raise ValidationError("you're already registered")
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!