Skip to content

Instantly share code, notes, and snippets.

@hirokazumiyaji
Last active August 29, 2015 14:10
Show Gist options
  • Save hirokazumiyaji/4d21455884eb020652ca to your computer and use it in GitHub Desktop.
Save hirokazumiyaji/4d21455884eb020652ca to your computer and use it in GitHub Desktop.
django email forms field.
# coding: utf-8
import re
from django.forms.fields import CharField
from django.forms.widgets import EmailInput
from django.utils.deconstruct import deconstructible
class EmailValidator(object):
message = _('Enter a valid email address.')
code = 'invalid'
user_part_regex = re.compile(r"^(?:(?:(?:(?:[a-zA-Z0-9_!#\$\%&'*+/=?\^`{}~|\-]+)(?:\.(?:[a-zA-Z0-9_!#\$\%&'*+/=?\^`{}~|\-]+))*)$"
r'|(?:"(?:\\[^\r\n]|[^\\"])*")))$',
re.IGNORECASE)
domain_part_regex = re.compile(r"(?:(?:(?:(?:[a-zA-Z0-9_!#\$\%&'*+/=?\^`{}~|\-]+)(?:\.(?:[a-zA-Z0-9_!#\$\%&'*+/=?\^`{}~|\-]+))*)|(?:\[(?:\\[\x01-\x09\x0B-\x0c\x0e-\x7f]|[\x21-\x5a\x5e-\x7e])*\])))$",
re.IGNORECASE)
def __init__(self, message=None, code=None):
if message is not None:
self.message = message
if code is not None:
self.code = code
def __call__(self, value):
value = force_text(value)
if not value or '@' not in value:
raise ValidationError(self.message, code=self.code)
user_part, domain_part = value.rsplit('@', 1)
if not self.user_regex.match(user_part):
raise ValidationError(self.message, code=self.code)
if not self.domain_part_regex.match(domain_part):
raise ValidationError(self.message, code=self.code)
def __eq__(self, other):
return (
isinstance(other, EmailValidator) and
(self.message == other.message) and
(self.code == other.code)
)
@deconstructible
class EmailField(CharField):
widget = EmailInput
default_validators = [EmailValidator()]
def clean(self, value):
value = self.to_python(value).strip()
value = super(EmailField, self).clean(value)
user_part, domain_part = value.rsplit('@', 1)
return '{}@{}'.format(user_part, domain_part.lower())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment