Validation
Validate data with built-in rules and custom clean methods.
Syntax
def clean_<field>(self): ...Each field validates its own type automatically. Add custom rules with a clean_<field>() method (for one field) or clean() (for cross-field checks). Raise ValidationError to reject input.
Errors are collected and displayed next to the offending field.
Example
from django import forms
from django.core.exceptions import ValidationError
class SignupForm(forms.Form):
username = forms.CharField(max_length=30)
password = forms.CharField(widget=forms.PasswordInput)
def clean_username(self):
name = self.cleaned_data["username"]
if " " in name:
raise ValidationError("Username cannot contain spaces.")
return nameWhen to use it
- A developer adds a clean_email method to reject email addresses from a blocked domain list.
- A form validates that the end_date is always after the start_date in the cross-field clean() method.
- A developer uses validators=[MinLengthValidator(8)] on a password field to enforce a minimum length rule.
More examples
Field-level validation method
Uses a clean_<fieldname>() method to reject reserved usernames with a custom error message.
from django import forms
class RegistrationForm(forms.Form):
username = forms.CharField()
def clean_username(self):
value = self.cleaned_data["username"]
if value.lower() in ("admin", "root", "superuser"):
raise forms.ValidationError("This username is reserved.")
return valueCross-field validation in clean()
Overrides clean() to compare two fields and raise an error if the end date is not after the start date.
class EventForm(forms.Form):
start_date = forms.DateField()
end_date = forms.DateField()
def clean(self):
cleaned = super().clean()
start = cleaned.get("start_date")
end = cleaned.get("end_date")
if start and end and end <= start:
raise forms.ValidationError("End date must be after start date.")
return cleanedReusable validator function
Defines a standalone validator function and attaches it to a field via the validators list.
from django.core.exceptions import ValidationError
def no_spaces(value):
if " " in value:
raise ValidationError("Value may not contain spaces.")
class TagForm(forms.Form):
name = forms.CharField(validators=[no_spaces])
Discussion