- 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
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 6 months ago
Comments
News from the future: In Django 1.2+ you could use a "validator".
Here's an example.
#
Please login first before commenting.