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. SelectDateWidget with format: day, month, year by zenx 4 years, 4 months ago
  2. Month / Year dropdown widget by gregb 4 years, 8 months ago
  3. SplitSelectDateTimeWidget by bradmontgomery 5 years, 5 months ago
  4. Form field sets by gonz 4 years, 3 months ago
  5. Arbitrary length formset by Rupe 4 years, 7 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?)