Login

Validation for full e-mails (e.g. "Joe Hacker <[email protected]>")

Author:
akaihola
Posted:
December 21, 2011
Language:
Python
Version:
1.3
Score:
1 (after 1 ratings)

Out of the box, Django e-mail fields for both database models and forms only accept plain e-mail addresses. For example, [email protected] is accepted.

On the other hand, full e-mail addresses which include a human-readable name, for example the following address fails validation in Django:

Joe Hacker <[email protected]>

This package adds support for validating full e-mail addresses.

Database model example

from django import models
from full_email.models import FullEmailField

class MyModel(models.Model):
    email = FullEmailField()

Forms example

from django import forms
from full_email.formfields import FullEmailField

class MyForm(forms.Form):
    email = FullEmailField(label='E-mail address')

I maintain this code in a GitHub gist. It includes some unit tests as well.

 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
50
51
52
53
54
55
56
### full_email/__init__.py #####################################################

"""Full e-mail address validation for Django"""


### full_email/formfields.py ###################################################

from django import forms

from .validators import validate_full_email


class FullEmailField(forms.EmailField):
    default_validators = [validate_full_email]


### full_email/validators.py ###################################################

from django.core.validators import email_re, EmailValidator, ValidationError
from django.utils.translation import ugettext_lazy as _


class FullEmailValidator(EmailValidator):
    def __call__(self, value):
        try:
            super(FullEmailValidator, self).__call__(value)
        except ValidationError, e:
            # Trivial case failed. Try for possible Full Name <email@address>
            if value and u'<' in value and value.endswith(u'>'):
                parts = value.rsplit(u'<', 1)
                fullname_part = parts[0].rstrip()
                email_part = parts[1][:-1]
                super(EmailValidator, self).__call__(email_part)
            else:
                raise


validate_full_email = FullEmailValidator(email_re,
                                         _(u'Enter a valid e-mail address.'),
                                         'invalid')


### full_email/models.py #######################################################

from django.db import models
from . import formfields
from .validators import validate_full_email


class FullEmailField(models.EmailField):
    default_validators = [validate_full_email]

    def formfield(self, **kwargs):
        defaults = {'form_class': formfields.FullEmailField}
        defaults.update(kwargs)
        return super(FullEmailField, self).formfield(**defaults)

More like this

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

Comments

Please login first before commenting.