- Author:
- watchedman
- Posted:
- September 21, 2011
- Language:
- Python
- Version:
- 1.3
- Score:
- 2 (after 2 ratings)
Simple password validation for user registration - requires that password be 7 or more characters and contain both letters and numbers. Original validation with regex approach developed by kurtis. Optimized no-regex version based on code from watchedman ran as fast or significantly faster on all systems on which we tested it.
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 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | from django import forms
""" slower clean() method using regex
def clean(self, value):
import re
if not re.search('[a-zA-Z]+', value) or not re.search('[0-9]+', value):
raise forms.ValidationError(u'Your password must include at least \
one letter and at least one number.')
"""
# Password Field (Extends CharField) (Optimized Version)
import string
class PasswordField(forms.CharField):
# Setup the Field
def __init__(self, *args, **kwargs):
super(PasswordField, self).__init__(min_length = 7, required = True,
label = u'Password',
widget = forms.PasswordInput(render_value = False),
*args, **kwargs)
# Validate - 1+ Numbers, 1+ Letters
def clean (self, value):
# Setup Our Lists of Characters and Numbers
characters = list(string.letters)
numbers = [str(i) for i in range(10)]
# Assume False until Proven Otherwise
numCheck = False
charCheck = False
# Loop until we Match
for char in value:
if not charCheck:
if char in characters:
charCheck = True
if not numCheck:
if char in numbers:
numCheck = True
if numCheck and charCheck:
break
if not numCheck or not charCheck:
raise forms.ValidationError(u'Your password must include at least \
one letter and at least one number.')
return super(PasswordField, self).clean(value)
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 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
We forgot a very important part of this. It needs to be added on to the end of the clean function(s):
return super(PasswordField, self).clean(value)
#
Whoops, I used the wrong syntax for the code. Anyways, here it is:
return super(PasswordField, self).clean(value)
#
Nice catch kurtis, I added in the missing line. Thanks.
#
Please login first before commenting.