Python Friday #39: Form Validation for Your Flask App

As soon as you work with forms you want to validate the user input. Otherwise you collect a lot of garbage in no time.

This post is part of my journey to learn Python. You can find the other parts of this series here.

 

Client-side validation

A user-friendly approach to form validation is to do it on the client side. Here you can inform the user that fields are missing, or that they put in the wrong values without the delay of sending the form to the server. For my simple form of the last post I use the HTML 5 attributes to validate the form data:

The required attribute in every field makes sure that the user enters some data. If you try to send this form without entering a value for each field, you cannot submit the form and get an explanation on what to do:

The browser tells you that you need to fill in this field

In the field email I want an email address. To enforce that, I changed the type from text to email. If you enter something that has no @ in it, you get this message:

The email field checks that you enter an email address

 

Everything OK? NO!

As long as you access the form through a modern web browser the validation works. However, if someone uses HTTPie the whole client-side validation is circumvented, and incorrect data goes to the server:

We get a successful message on the client, but the form data we processed on the server is empty:

127.0.0.1 – – [19/Sep/2020 08:42:46] “POST /contact HTTP/1.1” 302 –
[]:

 

Server-side validation

The only way to prevent bad data from being processed is to validate it on the server. While you can skip the client-side validation (and annoy your users), you never should skip server-side validation.

Even a small form like the contact form requires a lot of validation:

If now some input data is not valid, we send the user back to the form where they can add the missing values. The valid values are already in the form, thanks to the attribute value we set for each form field:

The last thing we need in our form is to display the error message – if it exists. For that we can add this snipped above the form fields:

If we now pass the client-side validation of the form but not the validation on the server-side, we get an error message and can correct the data:

Our form now keeps its values and shows us what we need to fix

 

Next

I hope you agree with the importance of the server-side validation. Unfortunately, the code for validation grows rapidly when you add more fields to your form. In the next post I look at a pattern to unclutter your view functions and still protect your data.

2 thoughts on “Python Friday #39: Form Validation for Your Flask App”

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.