How to validate html forms in python Flask?

12,458

Using Webargs

from webargs import flaskparser, fields

FORM_ARGS = {
    'email': fields.Email(required=True),
    'username': fields.Str(required=True),

@app.route("/data", methods=["GET", "POST"])
def get_data():
    if request.method == "POST":
        parsed_args = flaskparser.parser.parse(FORM_ARGS, request)

But as long as you know the format of the incoming data you can still use WTFs for capturing the posted info (you dont need to render WTForms on a page for it to work), for example:

# import blurb    

class Form(FlaskForm):
    username = StringField('Username', validators=[InputRequired()])
    email = EmailField('Email', validators=[InputRequired(), Length(4, 128), Email()])

@app.route("/data", methods=["GET", "POST"])
def get_data():
    if request.method == "POST":
        form = Form()  # will register fields called 'username' and 'email'.
        if form.validate_on_submit():
            # do something
Share:
12,458
Mohammad Ghonchesefidi
Author by

Mohammad Ghonchesefidi

www.SamaSarin.com

Updated on June 15, 2022

Comments

  • Mohammad Ghonchesefidi
    Mohammad Ghonchesefidi almost 2 years

    I have a HTML form inside a landing page and I want to send the forms data by ajax to /data rout.
    The problem is validating this HTML form in backend.
    I know about Flask WTF form but using this method will generate form on backend which is not my case.

    from flask import Flask, request, url_for
    ...
    @app.route("/data", methods=["GET", "POST"])
    def get_data():
    if request.method == "POST":
        username = request.form["username"]
        ...  
    

    My html form:

    <form method="POST" action="">
    <input type="text" name="username">
    <input type="submit" value="Send">
    </form>  
    

    One hard way is to validate every field using regex and write several if conditions for them. I'm wondering for easier way?