BirthYearField

 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 import newforms as forms
import time
import re

class BirthYearField(forms.Field):
    """A form field for entry of a year of birth, 
     must be before this year and not more than 110 years ago"""
    
    
    year_re = re.compile("\d\d\d\d")
    
    def clean(self, value):
        if not value:
            raise forms.ValidationError('Enter a four digit year, eg. 1984.')
        
        if not self.year_re.match(str(value)):
            raise forms.ValidationError('%s is not a valid year.' % value   )
        year = int(value)
        # check not after this year
        thisyear = time.localtime()[0]
        if year > thisyear:
            raise forms.ValidationError("%s is in the future, please enter your year of birth." % value )
        # or that this person isn't over 110
        if year < thisyear-110:
            raise forms.ValidationError("If you were born in %s you are now %s years old! Please enter your real birth year." % (year, thisyear-year))
        return year

Comments

(Forgotten your password?)

You may use Markdown syntax here, but raw HTML will be removed.