使用WTForms表单验证,可以在数据建模时就设置验证信息和错误提示
创建模型时,设置验证内容,如必填、格式、长度
from flask_wtf import Form
from wtforms import StringField, PasswordField, BooleanField
from wtforms import validators class UserRegForm(Form):
username = StringField('用户名',
[validators.DataRequired('用户名必填!'), validators.Length(min=4, max=8, message='长度为4-8之间')]) email = StringField('邮箱', [validators.Email('邮箱格式不正确')]) password = PasswordField('密码',
[validators.DataRequired('密码必填!'), validators.Length(min=6, max=16, message='长度为6-16之间')]) confirm = PasswordField('确认密码', [validators.EqualTo('password', message='密码输入不一致')])
accept = BooleanField('同意协议', [validators.DataRequired('同意协议才可以注册')])
前台页面,渲染数据信息和错误信息
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>用户注册</title>
</head>
<body>
<form action="#" method="POST">
{#form要求加上form.csrf_token方脚本跨域攻击#}
{{ form.csrf_token }}
<table border="1">
<tr>
<td>{{ form.username.label }}</td>
<td>{{ form.username }}</td>
{# 如果有错误信息,就遍历出来#}
<td>
{% if form.username.errors %}
{% for error in form.username.errors %}
<li>{{ error }}</li>
{% endfor %}
{% endif %}
</td>
</tr>
<tr>
<td>{{ form.email.label }}</td>
<td>{{ form.email }}</td>
<td>
{% if form.email.errors %}
{% for error in form.email.errors %}
<li>{{ error }}</li>
{% endfor %}
{% endif %}
</td>
</tr>
<tr>
<td>{{ form.password.label }}</td>
<td>{{ form.password }}</td>
<td>
{% if form.password.errors %}
{% for error in form.password.errors %}
<li>{{ error }}</li>
{% endfor %}
{% endif %}
</td>
</tr>
<tr>
<td>{{ form.confirm.label }}</td>
<td>{{ form.confirm }}</td>
<td>
{% if form.confirm.errors %}
{% for error in form.confirm.errors %}
<li>{{ error }}</li>
{% endfor %}
{% endif %}
</td>
</tr>
<tr>
<td></td>
<td>{{ form.accept }}{{ form.accept.label }}</td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="提交"></td>
</tr>
</table>
</form>
</body>
</html>
路由
from flask import Flask, render_template, request app = Flask(__name__, static_url_path='') # 初始化app, @app.route('/reg/', methods=['GET', 'POST'])
def user_reg():
from validations.froms import UserRegForm
form = UserRegForm(request.form)
if request.method == 'POST' and form.validate():
return str(form.data)
return render_template('user-reg.html', form=form)
访问并触发验证
输入符合要求的数据访问