Skip to content
thesarfo

Note

Flask Form Validation Feedback

Showing per-field validation errors in a Bootstrap-styled Jinja template using the is-invalid class.

views 0

Now that you’ve built the sign up and login forms, you need to be able to put some checks in place so that when the user types for eg: an incorrect email they get some kind of feedback.

For now when the user enters an invalid information they just get redirected to the same page when they submit because the form was invalid. In order to fix that, we need to head over to the register template.

Now for each of the input fields in the template, each of those fields will have a list of errors if that field was invalid. So you can open up a conditional and print those errors.

In Bootstrap, it can be done by adding a class called “is-invalid” to your field and then you put a div underneath that with a class of “invalid-feedback” and then put in the error there. See below:

<div class="form-group">
{{ form.username.label(class="form-control-label") }}
{% if form.username.errors %}
{{ form.username(class="form-control form-control-lg is-invalid") }}
<div class="invalid-feedback">
{% for error in form.username.errors%}
<span>{{error}}</span>
{% endfor %}
</div>
{% endif %}
{{ form.username(class="form-control form-control-lg") }}
</div>

What we did is that we added a class called “is-invalid” to our field, and then we opened an if statement to check if there are errors in our field.

We also created a div right underneath our field which we gave a class of “invalid-feedback”. Now inside that div we looped through the errors in our field, and printed the specific error inside a span tag.

But if there were no errors, it will just skip the loop to print what we had before. That is, what the else statement of the original if statement we opened above contains. See below for some pseudocode

add class "is-invalid" to your field
if form.field.errors:
create div with class "invalid-feedback"
for error in form.field.errors
print error
end for loop
else:
display form.field
end if statement