I've just come across the same problem, and here is my solution for a custom field validator that checks for a minimum age value:
from django.utils.deconstruct import deconstructible
from django.utils.translation import ugettext_lazy as _
from django.core.validators import BaseValidator
from datetime import date
def calculate_age(born):
today = date.today()
return today.year - born.year - \
((today.month, today.day) < (born.month, born.day))
@deconstructible
class MinAgeValidator(BaseValidator):
message = _("Age must be at least %(limit_value)d.")
code = 'min_age'
def compare(self, a, b):
return calculate_age(a) < b
The calculate_age snippet is from this post.
Usage:
class MyModel(models.Model):
date_of_birth = models.DateField(validators=[MinAgeValidator(18)])