Open In App

Custom Field Validations in Django Models

Last Updated : 15 Nov, 2025
Comments
Improve
Suggest changes
14 Likes
Like
Report

Custom field validations ensure that data entered into a model field meets specific rules before being saved to the database. They extend Django’s built-in validations, allowing developers to enforce additional rules.

  • Can verify formats, length limits, or complex conditions (such as ensuring an email belongs to a certain domain).
  • Run automatically when creating or updating model instances.
  • Help maintain clean and consistent data without adding extra validation logic in forms or views.
  • Builds on Django’s built-in field validations.

Syntax

field_name = models.Field(validators=[validator_function1, validator_function2])

  • validators is a list of validator functions that will be executed when the field value is set.
  • Each validator function accepts a single argument, value, which is the data entered for the field.

Understanding Django Custom Field Validation

Consider a project named 'geeksforgeeks' having an app named 'geeks'. Let’s create a custom validator that accepts only email addresses ending with @gmail.com.

1. Define the Model

In models.py, start with a simple model having a CharField for email:

Python
from django.db import models
from django.db.models import Model

class GeeksModel(Model):
    geeks_mail = models.CharField(max_length = 200)

2. Create a Validator Function

Create a custom validator function that will check whether the email address ends with @gmail.com. If it doesn't, the function will raise a ValidationError.

Python
from django.core.exceptions import ValidationError

def validate_geeks_mail(value):
    if not value.endswith("@gmail.com"):
        raise ValidationError("This field accepts only Gmail addresses.")

3. Attach the Validator to the Model Field

Attach this validator function to the geeks_mail field in model using the validators parameter.

Python
from django.db import models
from django.core.exceptions import ValidationError

def validate_geeks_mail(value):
    if not value.endswith("@gmail.com"):
        raise ValidationError("This field accepts only Gmail addresses.")

class GeeksModel(models.Model):
    geeks_mail = models.CharField(max_length=200, validators=[validate_geeks_mail])
  • The custom validator ensures that the geeks_mail field only accepts email addresses ending with @gmail.com.
  • Any email address not ending with @gmail.com will trigger a ValidationError.
  • This approach allows applying any type of custom validation to a field’s value.

After every change in models.py, run these commands makemigrations and migrate commands to update the changes in database.

Opening Django Shell

Validation can be tested interactively by the Django shell:

python manage.py shell

This allows creating model instances and checking how Django responds to valid and invalid input.

Invalid Case : Passing a non-Gmail address

If a value like "[email protected]" is used for geeks_mail, the custom validation system will raise an error, as only addresses ending with @gmail.com are allowed.

ValidationError
Custom Validation Error

Valid Case: Passing a Correct Gmail Address

Values that satisfy the custom validator (ending with @gmail.com) will not raise any ValidationError.

Correct
Valid Gmail Input

The Django admin interface can be used to verify that non-Gmail email addresses are automatically rejected, as the custom validator enforces the required validation rule.

Suggested Quiz
3 Questions

How can a custom validation be added to a model field in Django?

  • A

    By overriding the save() method only

  • B

    By writing validation logic inside views.py

  • C

    By modifying the database table directly

  • D

    By passing a validators list with custom functions to the field definition

Explanation:

The validators parameter on a model field accepts a list of functions. Each function is called with the field value, and raises a ValidationError if the value does not meet the custom rule.

What should a custom validator function do if the provided value does not pass validation?

  • A

    Return False silently

  • B

    Raise a ValidationError with an error message

  • C

    Print an error and return None

  • D

    Auto-correct the value to a default

Explanation:

Custom validator functions must raise ValidationError to signal invalid data, so Django rejects saving or form submission.

When is custom field validation applied in Django models?

  • A

    Before saving or updating model instances (on create or update)

  • B

    Only during form rendering

  • C

    Only when manually calling a special method

  • D

    Only when using Django admin

Explanation:

Custom validators are run automatically when model instances are created or updated to ensure data meets custom rules before being saved.

Quiz Completed Successfully
Your Score :   2/3
Accuracy :  0%
Login to View Explanation
1/3 1/3 < Previous Next >

Explore