Python > Web Development with Python > Flask > Forms
Flask Form Example: Field-Specific Validation
This snippet enhances the previous example by adding field-specific validation to ensure user input meets certain criteria, demonstrating custom validation within a Flask form.
Form Definition with Custom Validation (forms.py)
This defines a `RegistrationForm` with a `username` and `age` field. The `username` field uses a custom validator `validate_username` which checks if the username is at least 5 characters long. The `age` field validates that the input is a number between 18 and 120. The `ValidationError` allows us to raise custom error messages.
from flask_wtf import FlaskForm
from wtforms import StringField, IntegerField, SubmitField
from wtforms.validators import DataRequired, Length, NumberRange, ValidationError
def validate_username(form, field):
if len(field.data) < 5:
raise ValidationError('Username must be at least 5 characters long.')
class RegistrationForm(FlaskForm):
username = StringField('Username', validators=[DataRequired(), validate_username])
age = IntegerField('Age', validators=[DataRequired(), NumberRange(min=18, max=120)])
submit = SubmitField('Register')
Flask Application (app.py)
This Flask app defines a `/register` route that handles the `RegistrationForm`. Upon successful validation, it renders a 'success.html' template, passing the username and age. In a real application, you would perform registration actions here, like saving the user data to a database.
from flask import Flask, render_template, request
from forms import RegistrationForm
app = Flask(__name__)
app.config['SECRET_KEY'] = 'another_secret_key'
@app.route('/register', methods=['GET', 'POST'])
def register():
form = RegistrationForm()
if form.validate_on_submit():
username = form.username.data
age = form.age.data
return render_template('success.html', username=username, age=age) # Replace with actual registration logic
return render_template('register.html', form=form)
if __name__ == '__main__':
app.run(debug=True)
HTML Template (templates/register.html)
This HTML template renders the registration form and displays validation errors, if any. The `form.username.errors` and `form.age.errors` lists contain error messages generated by the validators. These error messages are then displayed to the user.
<!DOCTYPE html>
<html>
<head>
<title>Registration Form</title>
</head>
<body>
<h1>Registration Form</h1>
<form method="POST">
{{ form.csrf_token }}
<p>
{{ form.username.label }}<br>
{{ form.username(size=30) }}
{% if form.username.errors %}
<ul>
{% for error in form.username.errors %}
<li>{{ error }}</li>
{% endfor %}
</ul>
{% endif %}
</p>
<p>
{{ form.age.label }}<br>
{{ form.age() }}
{% if form.age.errors %}
<ul>
{% for error in form.age.errors %}
<li>{{ error }}</li>
{% endfor %}
</ul>
{% endif %}
</p>
<p>{{ form.submit() }}</p>
</form>
</body>
</html>
Success HTML Template (templates/success.html)
A simple success page that displays the username and age after successful registration.
<!DOCTYPE html>
<html>
<head>
<title>Registration Successful</title>
</head>
<body>
<h1>Registration Successful!</h1>
<p>Welcome, {{ username }}! You are {{ age }} years old.</p>
</body>
</html>
Concepts Behind the Snippet
This snippet demonstrates how to implement custom validation logic within Flask forms using `wtforms.validators.ValidationError`. This allows you to enforce specific rules that are not covered by the built-in validators. Displaying the errors near the fields is important for good user experience.
Real-Life Use Case
This can be used for creating forms that require a specific username format, password strength, email validation, or any other custom validation rule. For example, checking if a username already exists in the database.
Best Practices
Interview Tip
Be prepared to discuss different validation techniques and explain how to implement custom validators in Flask forms. Also, understand the importance of providing user-friendly error messages.
When to use them
Use field-specific validation whenever you need to enforce specific rules or constraints on user input that are not covered by the built-in validators.
Alternatives
Alternatives to custom validators include using regular expressions for more complex validation patterns, or using third-party validation libraries for specific data types.
Pros
Cons
FAQ
-
How do I display error messages in the template?
You can access the error messages through the `form.field_name.errors` list and iterate through it in your template to display each error message. -
Can I use regular expressions for validation?
Yes, you can use the `Regexp` validator from `wtforms.validators` to validate fields against a regular expression.