https://wtforms.readthedocs.io/en/2.3.x/
pip install Flask-WTF
# Field类型:
StringField # 字符串
PasswordField # 密码
IntegerField # 整形
DecimalField # 浮点,可以指定小数点位数
FloatField # 浮点
BooleanField # 布尔
RadioField # 单选
SelectField # 下拉列表
DatetimeField # 日期
....
# 验证:
DataRequired # 必填
EqualTo # 和谁保持一致
IPAddress # 验证ip地址
Length # 长度
NumberRange # 数字范围
URL # 必须符合路径格式
Email # 邮箱
Regexp # 正则
SECRET_KEY = "HAJSDLASDNADALK" # 随机字符串
csrf = CSRFProtect(app=app)
import re
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField
from wtforms.validators import DataRequired, Length, ValidationError, EqualTo, Regexp
class UserForm(FlaskForm):
# StringField:text文本框 ;DataRequired():必填 ;Length():长度; EqualTo():和谁保持一致
name = StringField(label='用户名', validators=[DataRequired(), Length(min=6, max=12, message="用户名长度必须在6~12位之间")])
password = PasswordField(label="密码", validators=[DataRequired(), Length(min=6, max=12, message="密码长度必须在6~12位之间")])
confirm_pwd = PasswordField(label="确认密码",
validators=[DataRequired(), Length(min=6, max=12, message="密码长度必须在6~12位之间"),
EqualTo('password', "两次密码不一致")])
phone = StringField(label="手机号码", validators=[DataRequired(), Length(min=11, max=11, message="手机号码必须11位长度")])
# 定义钩子方法,对用户名增加校验:validate_字段名
def validate_name(self, data):
if self.name.data[0].isdigit():
raise ValidationError("用户名不能以数字开头")
def validate_phone(self, data):
phone = data.data
if not re.search(r'^1[35678]\d{9}$', phone):
raise ValidationError("手机号码格式错误")
from flask import Blueprint, render_template
from util.form import UserForm
user_bp = Blueprint('user', __name__)
@user_bp.route('/',methods=["GET","POST"])
def hello_world():
uform = UserForm() # 表单类对象
if uform.validate_on_submit(): # 主要通过validate_on_submit 进行校验
print(uform.name)
print(uform.password)
return "提交成功"
return render_template("user/index.html", uform=uform)
用户页面