Validating Flask Forms
Validation checks form values before using them. An empty value gets a message, not a crash.
Make the app
This line imports Flask and request together. The route below validates the sent word.
from flask import Flask, request
app = Flask(__name__)Check the word first
The view reads the word with a default. An empty word gets a message, and a real word gets echoed.
@app.route("/echo", methods=["POST"])
def echo():
word = request.form.get("word", "")
if word == "":
return "Please type a word"
return "Posted: " + wordPost an empty form and a full form
The first post sends nothing, so the message shows. The second post sends hello, so the echo shows.
client = app.test_client()
print(client.post("/echo", data={}).data.decode())
print(client.post("/echo", data={"word": "hello"}).data.decode())Example
from flask import Flask, request
app = Flask(__name__)
@app.route("/echo", methods=["POST"])
def echo():
word = request.form.get("word", "")
if word == "":
return "Please type a word"
return "Posted: " + word
client = app.test_client()
print(client.post("/echo", data={}).data.decode())
print(client.post("/echo", data={"word": "hello"}).data.decode())Key points
- Check the value before using it.
- An empty value means the reader sent nothing.
- Show a message that names the missing value.
- form.get with a default never raises an error.
In this example, the view reads the word with a default of "". An empty word returns "Please type a word". A real word returns the echo. The test client posts an empty form and then a full form. The prints show the message and the echo.
Note
Validation runs in the view, before any saving.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What should a view do with an empty form value?