0
0
Djangoframework~5 mins

Custom form validation methods in Django

Choose your learning style9 modes available
Introduction

Custom form validation methods help you check user input in your forms beyond basic rules. They make sure data is correct and meaningful before saving or using it.

When you want to check if a username is already taken in a signup form.
When you need to ensure a password meets special rules like including numbers and letters.
When you want to confirm two fields match, like password and password confirmation.
When you want to validate a date is not in the past.
When you want to add custom error messages for specific input problems.
Syntax
Django
class MyForm(forms.Form):
    field_name = forms.CharField()

    def clean_field_name(self):
        data = self.cleaned_data['field_name']
        # custom validation logic
        if some_condition:
            raise forms.ValidationError('Error message')
        return data

    def clean(self):
        cleaned_data = super().clean()
        # cross-field validation
        if condition:
            raise forms.ValidationError('Error message')
        return cleaned_data

clean_field_name validates one field at a time.

clean method validates multiple fields together.

Examples
This checks if the username is 'admin' and raises an error if so.
Django
class SignupForm(forms.Form):
    username = forms.CharField()

    def clean_username(self):
        username = self.cleaned_data['username']
        if username == 'admin':
            raise forms.ValidationError('Username cannot be admin')
        return username
This checks if password and confirm_password fields match.
Django
class PasswordForm(forms.Form):
    password = forms.CharField(widget=forms.PasswordInput)
    confirm_password = forms.CharField(widget=forms.PasswordInput)

    def clean(self):
        cleaned_data = super().clean()
        pw = cleaned_data.get('password')
        cpw = cleaned_data.get('confirm_password')
        if pw and cpw and pw != cpw:
            raise forms.ValidationError('Passwords do not match')
        return cleaned_data
Sample Program

This form checks that the email ends with '@example.com' and the message is at least 10 characters long.

Django
from django import forms

class ContactForm(forms.Form):
    email = forms.EmailField()
    message = forms.CharField(widget=forms.Textarea)

    def clean_email(self):
        email = self.cleaned_data['email']
        if not email.endswith('@example.com'):
            raise forms.ValidationError('Email must be from example.com domain')
        return email

    def clean(self):
        cleaned_data = super().clean()
        message = cleaned_data.get('message')
        if message and len(message) < 10:
            raise forms.ValidationError('Message must be at least 10 characters long')
        return cleaned_data
OutputSuccess
Important Notes

Always return the cleaned data at the end of your validation methods.

Use raise forms.ValidationError to show errors to users.

Field-specific clean methods run before the general clean() method.

Summary

Custom validation methods let you check form data your way.

Use clean_fieldname for single fields and clean for multiple fields.

Raise ValidationError to show helpful error messages.