简体   繁体   中英

Flask WTForm validation

I have added validation using built-in rules in WTForms. However, the validation fails. It's not showing the message for the email field and accepting any random strings in the textbox. 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,

@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. To ensure that the validation works, you could add the conditional, if form.validate(): . This would return 'True' if the validations were met. A shortcut I use is 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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