6

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?

6
  • How do you want to validate the form exactly? What checks do you want to do? Commented Apr 20, 2019 at 9:35
  • Not empty. Email, Phone, Checked and much more ... Commented Apr 20, 2019 at 9:47
  • But I don't want to user regex for all inputs. It must be a better way? Commented Apr 20, 2019 at 9:49
  • If you don't want to use the validation methods provided by Flask-WTF you will need to write them yourself, indeed. Is there a specific reason you don't want to use Flask-WTF? Commented Apr 20, 2019 at 10:00
  • 1
    I would just import the WTForms validators you need and run them on your input yourself without creating a form. At least it saves you from creating your own regex for email, phone, date, etc. Commented Apr 20, 2019 at 17:30

1 Answer 1

14

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.