Form validation ensures that user-submitted data is accurate, complete, and secure. Django provides built-in mechanisms to validate form input and handle errors efficiently.
is_valid()Django validates form data when form.is_valid() is called. It checks required fields, data types, and custom validation rules.
# Defining a basic Django form with required fields
from django import forms
class ContactForm(forms.Form):
name = forms.CharField(max_length=100, required=True)
email = forms.EmailField(required=True)
message = forms.CharField(widget=forms.Textarea, required=True)
# Django template showing form errors
{% for field in form %}
{% if field.errors %}
{% for error in field.errors %}
{{ error }}
{% endfor %} {% endif %} {% endfor %}
# Custom validation for name field
def clean_name(self):
name = self.cleaned_data.get('name')
if len(name) < 3:
raise ValidationError("Name must be at least 3 characters long.")
return name
# Validating multiple fields together
def clean(self):
cleaned_data = super().clean()
if cleaned_data.get('password') != cleaned_data.get('confirm_password'):
raise ValidationError("Passwords do not match.")
return cleaned_data
If validation fails, Django automatically attaches error messages to the form. These can be displayed in templates to guide users in correcting their input.
Try entering invalid data below (e.g., a name shorter than 3 chars or mismatched passwords) to simulate how Django catches errors.
is_valid() before processing dataclean_fieldname for field-specific rulesclean() for cross-field validation