Last Updated : 12 Jul, 2025
Field validation ensures that the data entered into a model field meets specific rules before it’s saved to the database.
While Django provides built-in validations for common checks, custom field validation lets you enforce your own rules, such as verifying formats, length limits, or complex conditions like ensuring an email belongs to a certain domain.
Custom validations run automatically when creating or updating model instances, helping keep your data clean and consistent without adding extra validation logic in forms or views.
Syntax for Custom ValidatorsPrerequisite: Field Validations and Built-In Field Validations
field_name = models.Field(validators=[validator_function1, validator_function2])
Let’s look at an example where we create a custom validator to only accept email addresses ending with @gmail.com. Consider a project named geeksforgeeks having an app named geeks.
Step 1: Define the ModelRefer to the following articles to check how to create a project and an app in Django.
In your Django app’s 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)
Step 2: Create a Validator Function
Now, let’s 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.")
Step 3: Attach the Validator to the Model Field
Next, we attach this validator function to the geeks_mail field in our 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])
Now, the geeks_mail field will only accept email addresses containing @gmail.com. Any other email address will trigger a ValidationError. Let us try to create an instance without gmail.com and check if our validation worked or not.
Note that after every change in models.py one needs to run makemigrations and migrate commands.
In your browser go to http://localhost:8000/admin/geeks/geeksmodel/add/ and enter "abc@geeksforgeeks.org":
Custom ValidationSo the validation worked and this field can only accept email ids ending with @gmail.com. This way one can apply any kind of custom validation on value.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4