0 day streak
python / beginner
Snippet

Custom Form Validation

Custom validation allows you to check specific field data against business rules before saving it.

snippet.py
python
1
2
3
4
5
6
7
8
9
10
11
from django import forms
from django.core.exceptions import ValidationError
class ContactForm(forms.Form):
email = forms.EmailField()
def clean_email(self):
data = self.cleaned_data['email']
if 'spam' in data:
raise ValidationError('Invalid email address!')
return data
django
Breakdown
1
def clean_email(self):
Django looks for methods starting with 'clean_' followed by the field name.
2
raise ValidationError(...)
This stops the form from being processed and shows an error to the user.