Created

Embed URL

HTTPS clone URL

SSH clone URL

You can clone with HTTPS or SSH.

Download Gist

Year validator for a Django (1.2+) IntegerField.

View validators.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
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
Something went wrong with that request. Please try again.