You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesi贸n a prueba de IA

Antes: $249

Currency
$209
Suscr铆bete

Termina en:

0 D铆as
14 Hrs
45 Min
22 Seg
Curso de Flask

Curso de Flask

Luis Mart铆nez

Luis Mart铆nez

Validaci贸n de formularios en Flask

16/18
Resources

Data validation is a fundamental aspect in web development that guarantees the integrity and quality of the information we receive from users. When building applications, especially those that allow the creation of content such as notes or publications, it is crucial to implement mechanisms that verify if the data entered meets our requirements before processing or storing it in the database.

How to validate client-side information in Flask?

When developing web applications, it is common for users to enter information that may not meet our validity criteria. For example, titles that are too short or content without enough information. Server-side validation is essential to ensure that only data that meets our requirements is processed.

In Flask, we can implement manual validations relatively easily. These validations are performed before the data is stored in the database, allowing us to display appropriate error messages to the user and avoid processing invalid information.

Implementing Basic Validations in Flask Routes

To implement basic validations in our Flask routes, we can check the conditions directly in the route code. Let's see a practical example:

@app.route('/notes/create',  methods=['POST'])def create_note(): title = request.form['title'] content = request.form['content']    
 # Title validation if len(title.strip()) > 10: # Title is valid, we continue        
 # Content validation if len(content.strip()) > 300: # Content is valid, we save the note # Code to save the note in the database flash('The note was created successfully', 'success') return redirect(url_for('notes')) else: flash('The content is too short, minimum 300 characters', 'error') else: flash('The title is too short, minimum 10 characters', 'error')    
 # If we got here, there was a validation error return render_template('create_note.html')

In this code, we are validating two conditions:

  1. That the title has at least 10 characters (after removing whitespace).
  2. That the content has at least 300 characters

If any of these conditions are not met, we display an error message to the user and re-render the form so that they can correct the information.

Using Flask's flash message system

Flask includes a flash message system that allows us to send messages between requests. These messages are stored in the session and are displayed on the next request. In our example, we use this system to display error or success messages to the user:

flash('Title is too short, minimum 10 characters', 'error').

The second parameter ('error') indicates the type of message, which allows us to apply different styles depending on whether it is a success, error, warning, etc. message.

Integration with the HTML template

For these messages to be displayed correctly, we need to include the corresponding code in our base template:

{% with messages = get_flashed_messages(with_categories=true) %} {% if messages %} {% for category, message in messages %} <div class="alert alert-alert-{{{ category }}"> {{ message }} </div> {% endfor %} {% endif %}{% endwith %}

This code goes through all flash messages and displays them with the CSS class corresponding to the message type.

What alternatives exist for more complex validations?

Although manual validation is useful for simple cases, Flask offers integrations with more powerful libraries to handle complex validations. One of the most popular is Flask-WTF, which provides an integration between Flask and WTForms.

Flask-WTF allows you to define forms as Python classes, with declarative validation rules:

from flask_wtf import FlaskFormfrom wtforms import StringField, TextAreaFieldfrom wtforms.validators import DataRequired, Length
class NoteForm(FlaskForm): title = StringField('Title',  validators=[ DataRequired(message='Title is required'), Length(min=10,  message='Title must be at least 10 characters long') ]) content = TextAreaField('Content',  validators=[ DataRequired(message='Content is required'), Length(min=300,  message='Content must be at least 300 characters long') ])

This approach offers several advantages:

  • Separation of responsibilities: The validation logic is separated from the routing logic.
  • Reusability: We can use the same form in multiple routes.
  • Extensibility: It is easy to add new validation rules.
  • Internationalization: Facilitates translation of error messages

Implementation with Flask-WTF

To use Flask-WTF in our routes, the code would be simplified:

@app.route('/notes/create',  methods=['GET', 'POST'])def create_note(): form = NoteForm()    
 if form.validate_on_submit(): # All data is valid # Code to save the note to the database flash('The note was created successfully', 'success') return redirect(url_for('notes'))    
 # If there are validation errors, they will be automatically displayed in the template return render_template('create_note.html',  form=form)

And in the template:

<form method="post"> {{ form.csrf_token }}    
 <div class="form-group"> {{ form.title.label }} {{ form.title(class="form-control") }} {% if form.title.errors %} <div class="errors"> {% for error in form.title.errors %} <span class="error">{{ error }}</span> {% endfor %} </div> {% endif %} </div>    
 <div class="form-group"> {{ form.content.label }} {{ form.content(class="form-control") }} {% if form.content.errors %} <div class="errors"> {% for error in form.content.errors %} <span class="error">{{ error }}</span> {% endfor %} </div> {% endif %} </div>    
 <button type="submit" class="btn btn-primary">Createnote</button></button></form>

How to improve the user experience with validations?

Validation is not only about preventing incorrect data, but also about providing a good user experience. Some best practices include:

  1. Clear and specific messages: State exactly what is wrong and how to correct it.
  2. Real-time validation: Use JavaScript to validate as the user types.
  3. Preserve valid data: Do not force the user to re-enter information that was already correct.
  4. Proper visual design: Use colors, icons and styles to clearly distinguish errors.
  5. Accessibility: Ensure that error messages are accessible to all users.

The combination of client-side (JavaScript) and server-side (Flask) validations provides the best experience and security, as client-side validations enhance the user experience while server-side validations ensure data integrity.

Data validation is an essential component of any robust web application. Implementing effective validations improves both the user experience and the quality of the stored data. We invite you to experiment with Flask-WTF and other validation libraries to improve your applications. What other validation rules do you consider important for a note application? Share your ideas in the comments.

Contributions 0

Questions 0

Sort by:

Want to see more contributions, questions and answers from the community?