flask_wtf中无法识别自定义验证器

时间:2020-09-04 06:44:45

标签: python-3.x flask flask-wtforms

我有此注册表

class RegistrationForm(FlaskForm):
    username = StringField("username", validators=[InputRequired(), Length(min=4, max=7, message="must be between 4 and 7 Chars long")])
    email = StringField("Email", validators=[DataRequired(), Email()])
    password = PasswordField('Password', validators=[DataRequired()])
    password_repeat = PasswordField('repeat Password', validators=[DataRequired(), EqualTo('password')])
    submit = SubmitField('sign Up')

    def validate_username(self, username):
        user = User.query.filter_by(username=username.data).first()
        if user is not None:
            raise ValidationError('username allready taken.')

    def validate_email(self, email):
        user = User.query.filter_by(email=email.data).first()
        if user is not None:
            raise ValidationError('email already taken.')

    def validate_name(form, username):
        if 't' in username.data:
            raise ValidationError('no t pls')

我想构建一个自定义验证器,以检查例如输入的用户名是否包含字母“ t” 如果是这样,请显示ValidationError

 def validate_name(form, username):
        if 't' in username.data:
            raise ValidationError('no t pls') 

如果我正确理解了Custom validators上的文档

语法应该正确,但是在插入和提交数据时没有收到错误消息
我在if form.validate_on_submit():

中使用routes

1 个答案:

答案 0 :(得分:-1)

def validate_name(form, username):
    if 't' in username.data:
        raise ValidationError('no t pls')

您必须传递self而不是表单。

def validate_name(self, username):
    if 't' in username.data:
        raise ValidationError('no t pls')