0
0
DjangoHow-ToBeginner · 3 min read

How to Create Custom Validator in Django: Simple Guide

In Django, create a custom validator by defining a function that raises ValidationError when the input is invalid. Then, add this function to your model or form field's validators list to enforce your custom rule.
📐

Syntax

A custom validator in Django is a function that takes a value as input and raises ValidationError if the value does not meet your criteria. You then add this function to the validators argument of a model or form field.

Parts explained:

  • value: The input to validate.
  • ValidationError: Raised to indicate invalid input.
  • validators: A list of validator functions attached to a field.
python
from django.core.exceptions import ValidationError

def my_custom_validator(value):
    if not some_condition(value):
        raise ValidationError('Invalid value message')

# Usage in a model field
from django.db import models

class MyModel(models.Model):
    my_field = models.CharField(max_length=100, validators=[my_custom_validator])
💻

Example

This example shows a custom validator that checks if a string contains only letters. It raises an error if digits or symbols are found. The validator is used in a Django model field.

python
from django.core.exceptions import ValidationError
from django.db import models
import re

def validate_only_letters(value):
    if not re.fullmatch(r'[A-Za-z]+', value):
        raise ValidationError('Value must contain only letters.')

class Person(models.Model):
    name = models.CharField(max_length=50, validators=[validate_only_letters])
Output
If you try to save Person(name='John123'), Django raises ValidationError: ['Value must contain only letters.']
⚠️

Common Pitfalls

Common mistakes when creating custom validators include:

  • Not raising ValidationError properly, which means invalid data passes silently.
  • Using validators that do not accept a single value argument.
  • Forgetting to add the validator to the field's validators list.
  • Writing validators that modify data instead of only validating it.
python
from django.core.exceptions import ValidationError

def wrong_validator(value, extra):  # Wrong: extra argument
    if value != 'ok':
        raise ValidationError('Must be ok')

# Correct validator

def correct_validator(value):
    if value != 'ok':
        raise ValidationError('Must be ok')
📊

Quick Reference

StepDescription
Define validator functionCreate a function that takes one argument and raises ValidationError if invalid.
Raise ValidationErrorUse django.core.exceptions.ValidationError with a clear message.
Attach to fieldAdd your validator function to the field's validators list.
Test validationTry saving invalid data to see the error raised.

Key Takeaways

Create a validator as a function that raises ValidationError on invalid input.
Attach your custom validator to model or form fields using the validators argument.
Always raise ValidationError properly to ensure Django catches invalid data.
Validators must accept exactly one argument: the value to check.
Test your validator by trying to save invalid data and checking for errors.