Skip to content

Instantly share code, notes, and snippets.

@mhulse
Created June 13, 2011 18:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mhulse/1023327 to your computer and use it in GitHub Desktop.
Save mhulse/1023327 to your computer and use it in GitHub Desktop.
Year validator for a Django (1.2+) IntegerField.
from django.core.exceptions import ValidationError
import time
import re
def validate_year(value):
"""
Validator function for model.IntegerField()
* Validates a valid four-digit year.
* Must be a current or future year.
In your model:
year = models.IntegerField(_(u'Year'), help_text=_(u'Current or future year in YYYY format.'), validators=[validate_year], unique=True)
"""
# Matches any 4-digit number:
year_re = re.compile('^\d{4}$')
# If year does not match our regex:
if not year_re.match(str(value)):
raise ValidationError(u'%s is not a valid year.' % value)
# Check not before this year:
year = int(value)
thisyear = time.localtime()[0]
if year < thisyear:
raise ValidationError(u'%s is a year in the past; please enter a current or future year.' % value)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment