简体   繁体   English

Flask WTForm 验证

[英]Flask WTForm validation

I have added validation using built-in rules in WTForms.我使用 WTForms 中的内置规则添加了验证。 However, the validation fails.但是,验证失败。 It's not showing the message for the email field and accepting any random strings in the textbox.它没有显示 email 字段的消息并接受文本框中的任何随机字符串。 How can I test that validation is working?如何测试验证是否有效?

from flask import Flask, app, render_template, request
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField, validators
from wtforms.fields.simple import PasswordField 
from wtforms.validators import Email, InputRequired, length, EqualTo


app = Flask(__name__)

app.config['SECRET_KEY']="PQrs12t46uv"

class MyForm(FlaskForm):
    email = StringField(label=('Email Id'), validators=[ InputRequired("Enter the valid email address"), Email(), length(min=6, max=10)])
    password=PasswordField(label="Password", validators=[InputRequired()])
    confirm_password=PasswordField("Confirm Password", validators=[EqualTo('password',message="Should be same as the password.")])
    submit = SubmitField(label=('Register'))  

@app.route('/')
def base():
    form = MyForm()
    return render_template('formvalidation.html', form=form)

@app.route('/submitform', methods=["GET","POST"])
def submitform():
    if request.method == 'POST':
         return 'form accepted successfully.'

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

# formvalidation.html

<!DOCTYPE html>
<html>
    <head><title>My website</title></head>
    <body>
        <h1>Login form</h1>  
        <form action="http://127.0.0.1:5000/submitform" method="post">
        <p>{{form.email.label}}: {{form.email}}</p>
        <p>{{form.password.label}}: {{form.password}}</p>
        <p>{{form.confirm_password.label}}: {{form.confirm_password}}</p>
        <p>{{form.submit}}</p> 
    </form>
      
    </body>
</html>

In your submitform function,在您提交的表格submitform中,

@app.route('/submitform', methods=["GET","POST"])
def submitform():
    if request.method == 'POST':
         return 'form accepted successfully.'

request.method == 'POST' will only check if the form was submitted, not if the credentials were validated. request.method == 'POST'将仅检查表单是否已提交,而不检查凭据是否已验证。 To ensure that the validation works, you could add the conditional, if form.validate(): .为确保验证有效,您可以添加条件if form.validate(): This would return 'True' if the validations were met.如果满足验证,这将返回“True”。 A shortcut I use is if form.validate_on_submit(): .我使用的快捷方式是if form.validate_on_submit(): This checks that the form has been submitted and that the validations were met with one conditional, instead of checking that the method is equal to 'POST' and that the form has been validated.这将检查表单是否已提交并且验证是否满足一个条件,而不是检查方法是否等于“POST”并且表单是否已被验证。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM