Created
November 14, 2012 21:59
-
-
Save gterzian/4075126 to your computer and use it in GitHub Desktop.
Django ProEmailFormField
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django import forms | |
from django.core.exceptions import ValidationError | |
import re | |
''' | |
pass a list of excluded domain names upon instantiation. | |
subclasses forms.EmailField, which validates against empty values, and that it is a correct email. | |
then validate_pro will check whether not part of the excluded domains. | |
I used an extra method as opposed to a custom validator because it seems to be difficult to know which validator is run first | |
and we do want the default email validator to run first because otherwise there is a chance that the regexp will fail and crash the site. | |
''' | |
class ProEmailField(forms.EmailField): | |
def __init__(self, excludedDomain, **kwargs): | |
self.exclude = excludedDomain | |
super(ProEmailField, self).__init__(self,**kwargs) | |
def validate_pro(self, value): | |
domain = value.split('@')[1] | |
if domain in self.exclude: | |
raise ValidationError('it seems you have provided a %s address, please give us your professional email adress' % (domain)) | |
def clean(self, value): | |
#please note the extra validate_pro method | |
value = super(ProEmailField, self).clean(value) | |
self.validate_pro(value) | |
return value |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment