自定义表单验证器
1、index.html
<form action="" method="post">
<table>
<tbody>
<tr>
<td>{{ form.username.label }}</td>
<td>{{ form.username }}</td>
</tr>
<tr>
<td>{{ form.password.label }}</td>
<td>{{ form.password }}</td>
</tr>
<tr>
<td></td>
<td>{{ form.reg }}</td>
</tr>
</tbody>
</table>
</form>
{% for error in form.username.errors %}
<p>{{ error }}</p>
{% endfor %}
{% for error in form.password.errors %}
<p>{{ error }}</p>
{% endfor %}
2、app.py
from flask import Flask, render_template, request
from wtforms import Form, StringField, PasswordField, SubmitField, ValidationError
from wtforms.validators import Length
class RegForm(Form):
username = StringField('用户名:', validators=[
Length(min=6, max=12, message='用户名需要输入6到12个字符')
])
def validate_username(self, field):
if field.data != 'abcxyz':
raise ValidationError('用户名错误')
password = PasswordField('密码:', validators=[
Length(min=6, max=12, message='密码需要输入6到12个字符')
])
def validate_password(self, field):
if field.data != '123456':
raise ValidationError('密码错误')
reg = SubmitField('立即登录')
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def index():
form = RegForm(request.form)
if request.method == 'GET':
return render_template('index.html', form=form)
else:
if form.validate():
return '登录成功'
else:
return render_template('index.html', form=form)
if __name__ == '__main__':
app.run()