表单相关

1.自定义验证器

1.1 行内验证器

from wtforms import IntegerField, SubmitField
from wtforms.validators import ValidationError

class ForttwoForm(FlaskForm):
      answer = IntegerField('The Number')
      submit = SubmitField()
      def validate_answer(form, field):
            if field.data != 42:
                  raise ValidationError('Must be 42.')

当表单类中包含以'validate_字段属性名'形式命名的方法时,在验证字段数据时会同时调用这个方法来验证对应的字段

1.2 全局验证器

# 简单demo
from wtrorms.validators import ValidationError

def is_42(form, field):
      if field.data != 42:
            raise ValidationError('Must be 42')

class ForttwoForm(FlaskForm):
      answer = IntegerField('The Number', validators=[is_42])
      submit = SubmitField()

这里我们无法传入消息
我们改进如下

from wtrorms.validators import ValidationError

def is_42(message=None):
        if message is None:
                message = 'Must be 42'
        def _is_42(form, field):
                if field.data != 42:
                      raise ValidationError(message)
        return _is_42

class ForttwoForm(FlaskForm):
      answer = IntegerField('The Number', validators=[is_42])
      submit = SubmitField()

你可能感兴趣的:(表单相关)