Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate html forms in python Flask?

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?

like image 391
Mohammad Ghonchesefidi Avatar asked Apr 20 '19 09:04

Mohammad Ghonchesefidi


People also ask

How do you validate a form in html?

Mainly there are two ways to perform HTML form validation. The first is using the built-in functionality provided in HTML5, and the second is by using JavaScript. Using the first method, we don't need to write extra code.

Can we do validation in html?

The simplest HTML validation feature is the required attribute. To make an input mandatory, add this attribute to the element. When this attribute is set, the element matches the :required UI pseudo-class and the form won't submit, displaying an error message on submission when the input is empty.

What is WTForms in Flask?

WTForms is a Python library that provides flexible web form rendering. You can use it to render text fields, text areas, password fields, radio buttons, and others. WTForms also provides powerful data validation using different validators, which validate that the data the user submits meets certain criteria you define.

What is form Validate_on_submit?

The validate_on_submit() method of the form returns True when the form was submitted and the data was accepted by all the field validators. In all other cases, validate_on_submit() returns False . The return value of this method effectively serves to determine whether the form needs to be rendered or processed.


1 Answers

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
like image 174
Attack68 Avatar answered Oct 05 '22 23:10

Attack68