← Back to Chapters

Form Validation & Error Handling

? Form Validation & Error Handling

? Quick Overview

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.

? Key Concepts

  • Automatic validation using is_valid()
  • Field-level and form-level validation
  • Displaying user-friendly error messages

? Syntax / Theory

Django validates form data when form.is_valid() is called. It checks required fields, data types, and custom validation rules.

? Code Example – Basic Form Validation

? View Code Example
# 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)

? Code Example – Displaying Form Errors

? View Code Example
# Django template showing form errors
{% for field in form %}
{% if field.errors %}
{% for error in field.errors %}

{{ error }}

{% endfor %}
{% endif %} {% endfor %}

? Code Example – Custom Field Validation

? View Code Example
# 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

? Code Example – Non-Field Errors

? View Code Example
# 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

? Live Output / Explanation

If validation fails, Django automatically attaches error messages to the form. These can be displayed in templates to guide users in correcting their input.

? Interactive Example

Try entering invalid data below (e.g., a name shorter than 3 chars or mismatched passwords) to simulate how Django catches errors.

✅ Form is valid! cleaned_data processed.
 

? Use Cases

  • User registration forms
  • Contact and feedback forms
  • Secure data collection

✅ Tips & Best Practices

  • Always call is_valid() before processing data
  • Use clean_fieldname for field-specific rules
  • Use clean() for cross-field validation

? Try It Yourself

  • Create a form with password strength validation
  • Add custom error messages
  • Experiment with form-wide validation