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?
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With