flask之wtforms 表单验证(一)

时间:2021-05-02 04:31:44

一  安装wtforms

pip install wtforms

二  导入相关模块及对象

from wtforms import Form, widgets, validators
from wtforms.fields import simple

三 定义表单类

# 登陆表单
class LoginForm(Form):
name = simple.StringField(
label=u'用户名',
validators=[
validators.DataRequired(message=u'用户名不能为空'),
validators.Length(min=3, max=8, message=u'用户名长度必须大于%(min)d且小于%(max)d')
],
widget=widgets.TextInput(),
render_kw={'class': 'form-control'}
)
pwd = simple.PasswordField(
label=u'密码',
validators=[
validators.DataRequired(message=u'密码不能为空'),
validators.Length(min=3, max=8, message=u'密码至少大于3个字符'),
validators.Regexp(regex="\d+",
message=u'密码必须是数字')
],
widget=widgets.PasswordInput(),
render_kw={'class': 'form-control'}
) class Meta:
csrf = False def validate_pwd(self, *args, **kwargs):
pass

四 在视图函数中将表单对象传给模板进行渲染

@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'GET':
form = LoginForm()
return render_template('login.html', form=form)
else:
form = LoginForm(request.form)
if form.validate():
else:
print(form.errors)
return render_template('login.html', form=form)

五 在模板中展示

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="" method="post" novalidate>
<p>{{ form.name.label }} {{ form.name }} {{ form.name.errors.0 }}</p>
<p>{{ form.pwd.label }} {{ form.pwd }} {{ form.pwd.errors.0 }}</p>
<input type="submit" value="提交">
</form>
</body>
</html>

界面展示

flask之wtforms 表单验证(一)