Skip to content

Instantly share code, notes, and snippets.

@ilfuriano
Last active August 29, 2015 14:14
Show Gist options
  • Save ilfuriano/0cf6f7ae4ad2b611586d to your computer and use it in GitHub Desktop.
Save ilfuriano/0cf6f7ae4ad2b611586d to your computer and use it in GitHub Desktop.
Validate form field that include email or emails separated by 'token' kwargs, by default ',' a comma. Return a list [] of email(s). Check validity of the email(s) from django EmailField regex (work with 1.6)
from django import forms
from django.utils.translation import ugettext_lazy as _
from django.core import validators
from django.core.validators import EMPTY_VALUES
from django.forms.fields import Field
# Same as https://djangosnippets.org/snippets/3012/ but compatible with Django 1.6
class CommaSeparatedEmailField(Field):
description = _(u"E-mail address(es)")
def __init__(self, *args, **kwargs):
self.token = kwargs.pop("token", ",")
super(CommaSeparatedEmailField, self).__init__(*args, **kwargs)
def to_python(self, value):
if value in EMPTY_VALUES:
return []
value = [item.strip() for item in value.split(self.token) if item.strip()]
return list(set(value))
def clean(self, value):
"""
Check that the field contains one or more 'comma-separated' emails
and normalizes the data to a list of the email strings.
"""
value = self.to_python(value)
if value in EMPTY_VALUES and self.required:
raise forms.ValidationError(_(u"This field is required."))
for email in value:
validators.validate_email(email)
return value
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment