0

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> 

1 Answer 1

1

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. Note that you will need to define this 'form' variable that holds the desired Flask form. The following function should work.

@app.route('/submitform', methods=["GET","POST"]) def submitform(): form = MyForm() if form.validate_on_submit(): return 'form accepted successfully.' 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.