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

More like this

  1. Month / Year dropdown widget by gregb 3 years, 9 months ago
  2. Type checking templatetag filters by marcorogers 3 years, 2 months ago
  3. Custom model field for mysql time type. by xuqingkuang 3 years, 7 months ago
  4. BRPhoneNumberWidget by semente 1 year, 8 months ago
  5. Subdirectory and subcontext include template tag with examples by t_rybik 3 years, 2 months ago

Comments

mhulse (on June 13, 2011):

News from the future: In Django 1.2+ you could use a "validator".

Here's an example.

#

(Forgotten your password?)