0
0
Flaskframework~5 mins

Validation rules in Flask

Choose your learning style9 modes available
Introduction

Validation rules help check if the data users send to your app is correct and safe. They stop mistakes and bad data from causing problems.

When a user fills out a signup form and you want to check their email and password.
When accepting user input like age or phone number and you want to make sure it is a number.
When saving data to a database and you want to ensure required fields are not empty.
When you want to give friendly error messages if users enter wrong data.
When you want to prevent harmful data like scripts from being submitted.
Syntax
Flask
from flask_wtf import FlaskForm
from wtforms import StringField, IntegerField
from wtforms.validators import DataRequired, Email, NumberRange

class MyForm(FlaskForm):
    name = StringField('Name', validators=[DataRequired()])
    email = StringField('Email', validators=[DataRequired(), Email()])
    age = IntegerField('Age', validators=[DataRequired(), NumberRange(min=18, max=99)])

Validators are added as a list to each form field.

Common validators include DataRequired(), Email(), and NumberRange().

Examples
This makes sure the name field is not empty.
Flask
from wtforms.validators import DataRequired

name = StringField('Name', validators=[DataRequired()])
This checks if the email looks like a real email address.
Flask
from wtforms.validators import Email

email = StringField('Email', validators=[Email()])
This ensures the age is between 18 and 99.
Flask
from wtforms.validators import NumberRange

age = IntegerField('Age', validators=[NumberRange(min=18, max=99)])
Sample Program

This Flask app shows a form with name, email, and age fields. It uses validation rules to check the inputs. If the data is correct, it shows a success message. If not, it shows errors next to each field.

Flask
from flask import Flask, render_template_string, request
from flask_wtf import FlaskForm
from wtforms import StringField, IntegerField
from wtforms.validators import DataRequired, Email, NumberRange

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret-key'

class UserForm(FlaskForm):
    name = StringField('Name', validators=[DataRequired()])
    email = StringField('Email', validators=[DataRequired(), Email()])
    age = IntegerField('Age', validators=[DataRequired(), NumberRange(min=18, max=99)])

form_template = '''
<form method="POST">
  {{ form.hidden_tag() }}
  <p>
    {{ form.name.label }}<br>
    {{ form.name(size=20) }}<br>
    {% for error in form.name.errors %}<span style="color:red;">{{ error }}</span><br>{% endfor %}
  </p>
  <p>
    {{ form.email.label }}<br>
    {{ form.email(size=20) }}<br>
    {% for error in form.email.errors %}<span style="color:red;">{{ error }}</span><br>{% endfor %}
  </p>
  <p>
    {{ form.age.label }}<br>
    {{ form.age() }}<br>
    {% for error in form.age.errors %}<span style="color:red;">{{ error }}</span><br>{% endfor %}
  </p>
  <p><input type="submit" value="Submit"></p>
</form>
{% if success %}<p style="color:green;">Form submitted successfully!</p>{% endif %}
'''

@app.route('/', methods=['GET', 'POST'])
def index():
    form = UserForm()
    success = False
    if form.validate_on_submit():
        success = True
    return render_template_string(form_template, form=form, success=success)

if __name__ == '__main__':
    app.run(debug=True)
OutputSuccess
Important Notes

Always set a secret key in Flask to use Flask-WTF forms securely.

Validation errors appear automatically if you check form.errors or use form.validate_on_submit().

You can create custom validators if needed for special rules.

Summary

Validation rules check user input to keep data correct and safe.

Flask-WTF and WTForms make adding validation easy with simple validators.

Show helpful error messages so users can fix their input.