#使用 WTForms 進行表單驗證的例子 from wtforms import Form from wtforms import BooleanField from wtforms import TextField from wtforms import PasswordField from wtforms import validators #註冊表單 class RegisterForm(Form): username = TextField("Username",[validators.length(min=4, max=25)]) email = TextField("Email Address", [validators.length(min=6, max=25)]) password = PasswordField("New Password", [validators.Required(), validators.EqualTo("confirm", message="Passwords must match")]) confirm = PasswordField("Repeat Password") accept_tos = BooleanField("I accept the TOS", [validators.Required()]) #視圖函數 @app.route("/register", methods=["GET", "POST"]) def register(): form = RegisterForm(request.form) if request.method == "POST" and form.validate(): user = User(form.username.data, form.email.data, form.password.data) db_session.add(user) flash("Thanks for registering") return redirect(url_for("login")) return rendertemplate("regiser.html", form=form) #備忘表 # 一、若是數據是以POST方式提交的,那麼基於請求的form屬性的值建立表單,反過來,若是是以get提交的,就從args屬性建立 # 二、驗證表單數據,調用validate()方法,若是數據驗證經過,此方法將會返回True,不然返回False # 三、訪問表單的單個值,使用form.<NAME>.data #模版中的表單 {% macro render_field(field) %} <dt>{{ field.label }} <dd>{{ field(**kwargs)|safe }} {% if field.errors %} <ul class=errors> {% for error in field.errors %} <li>{{ error }}</li> {% endfor %} </ul> {% endif %} </dd> {% endmacro %}