WTForms常用的验证器

Posted wuheng-123

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了WTForms常用的验证器相关的知识,希望对你有一定的参考价值。

技术分享图片

 

from wtforms import Form,StringField,IntegerField
from wtforms import validators
from wtforms.validators import Length,EqualTo,Email,InputRequired,NumberRange,    Regexp,URL,UUID


class RegisterForm(Form):
    username = StringField(validators=[Length(max=10,min=3,message=用户名长度不正确)])
    password = StringField(validators=[Length(max=10,min=3,message=密码长度不正确)])
    password_repeat = StringField(validators=[Length(max=10,min=3,message=密码长度不正确),EqualTo(password)])


class LoginForm(Form):
    # email = StringField(validators=[Email(message=‘邮箱格式不正确‘)])
    # username = StringField(validators=[InputRequired(message=‘必须填写用户名‘)])#inputrequired必填字段
    # age = IntegerField(validators=[NumberRange(12,100)])#验证数字在某某区间之内
    # phone = StringField(validators=[Regexp(r‘1[85347]d{9}‘,message=‘手机号码格式不正确‘)])
    # home_page = StringField(validators=[URL()])#必须验证必须是一个跳转链接
    uuid = StringField(validators=[UUID()])#验证uuid的
from flask import Flask,request,render_template
from forms import RegisterForm,LoginForm


app = Flask(__name__)


@app.route(/)
def hello_world():
    return Hello World!


@app.route(/register/,methods=[get,post])
def register():
    if request.method == GET:
        return render_template(register.html)
    else:
        # username = request.form.get(‘username‘)
        # password = request.form.get(‘password‘)
        # password_repeat = request.form.get(‘password_repeat‘)
        # if 3 > len(username) or len(username)> 10:
        #     return ‘用户名长度不正确‘
        # if 3 > len(password) or len(password)> 10:
        #     return ‘密码长度不正确‘
        # if password != password_repeat:
        #     return ‘密码输入不一致‘
        form = RegisterForm(request.form)
        if form.validate():
            return success
        else:
            print(form.errors)#{‘username‘: [‘用户名长度不正确‘],
            # ‘password‘: [‘密码长度不正确‘], ‘password_repeat‘: [‘密码长度不正确‘]}
            #因为是字典,获取方式我就不写了
            return fail


@app.route(/login/,methods=[get,post])#如果methods没有post方法,会报状态码405错误,
# 静态文件不允许请求post方法
def login():
    if request.method == "GET":
        return render_template(login.html)
    else:
        login_form = LoginForm(request.form)
        if login_form.validate():
            return success
        else:
            return {errors}.format(errors=login_form.errors.get(phone)[0])#获取具体错误信息

if __name__ == __main__:
    app.run(debug=True)

 

以上是关于WTForms常用的验证器的主要内容,如果未能解决你的问题,请参考以下文章

flask wtforms组件详解

WTForms:安装“email_validator”以获得电子邮件验证支持

flask框架中使用wtforms

wtforms-表单生成及验证

使用 WTForms 进行表单验证的例子

python WTForms`RequireIf`验证器。