Field which accepts list of e-mail addresses separated by any character, except those which valid e-mail address can contain.
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
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 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
For Django 1.2 you need to replace
with
#
A simplier version that allows comma or semicolon-separated emails that can be used directly as "To:" value:
#
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):
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.
#
Please login first before commenting.