Multiple emails form field

 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
import re

from django.forms.fields import email_re
from django.forms import CharField, Textarea, ValidationError
from django.utils.translation import ugettext as _


email_separator_re = re.compile(r'[^\w\.\-\+@_]+')
     
                                                                                        
def _is_valid_email(email):    
    return email_re.match(email)


class EmailsListField(CharField):

    widget = Textarea

    def clean(self, value):
        super(EmailsListField, self).clean(value)

        emails = email_separator_re.split(value)

        if not emails:
            raise ValidationError(_(u'Enter at least one e-mail address.'))

        for email in emails:
            if not _is_valid_email(email):
                raise ValidationError(_('%s is not a valid e-mail address.') % email)

        return emails

More like this

  1. Validation for full e-mails (e.g. "Joe Hacker <joe@hacker.com>") by akaihola 2 years, 4 months ago
  2. email_links by sansmojo 6 years, 10 months ago
  3. Simple e-mail template tag by dchandek 5 years, 12 months ago
  4. Template Tag to protect the E-mail address by nitinhayaran 4 years, 2 months ago
  5. No Password E-mail by jefferya 5 years, 2 months ago

Comments

ludwik (on May 20, 2010):

For Django 1.2 you need to replace

from django.forms.fields import email_re

with

from django.core.validators import email_re

#

kmike (on March 20, 2012):

A simplier version that allows comma or semicolon-separated emails that can be used directly as "To:" value:

import re
from django.core.validators import validate_email

SEPARATOR_RE = re.compile(r'[,;]+')

def validate_email_list(value):
    emails = SEPARATOR_RE.split(value)
    for email in emails:
        validate_email(email)

#

bastien (on October 25, 2012):

I use a mix of both the snippet and Kmike's comment:

import re

from django.core.validators import email_re from django.forms import CharField, Textarea, ValidationError from django.utils.translation import ugettext as _ from django.core.validators import validate_email

class EmailsListField(CharField):

widget = Textarea

def clean(self, value):
    super(EmailsListField, self).clean(value)

    emails = re.compile(r'[^\w\.\-\+@_]+').split(value)

    if not emails:
        raise ValidationError(_(u'Enter at least one e-mail address.'))

    for email in emails:
        validate_email(email)

    return emails

the regex is more permissive, it works with Django 1.3, the logic allows for clear error messages although I don't use any with the validate_email() here one can be inserted.

#

(Forgotten your password?)