Login

BirthYearField

Author:
steve_cassidy51
Posted:
December 12, 2007
Language:
Python
Version:
.96
Score:
0 (after 0 ratings)

A form field to prompt for a year of birth with suitable sanity checks. Usage eg:

yob = BirthYearField(label="What year were you born?")

 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. Template tag - list punctuation for a list of items by shapiromatron 3 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 3 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 10 months, 1 week ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 11 months ago
  5. Help text hyperlinks by sa2812 11 months, 3 weeks ago

Comments

mhulse (on June 13, 2011):

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

Here's an example.

#

Please login first before commenting.