Django forms allow you to perform additional custom validation by overriding the clean method. This method is automatically called when the form’s is_valid() method is used.
Here’s how you can add custom validation to your form:
from django import forms
class ContactForm(forms.Form):
name = forms.CharField(max_length=100)
email = forms.EmailField()
message = forms.CharField(widget=forms.Textarea)
def clean(self):
cleaned_data = super().clean()
name = cleaned_data.get('name')
message = cleaned_data.get('message')
# Custom validation: Ensure name is included in the message
if name and message and name not in message:
raise forms.ValidationError("The message must include your name.")
return cleaned_data
Explanation:
- The
clean method processes all the fields in the form and ensures the data is valid.
cleaned_data contains the validated data for all fields.
- Custom validation logic is applied, and if the data doesn’t meet the criteria, a
ValidationError is raised.