Skip to content

Instantly share code, notes, and snippets.

@dokterbob
Created March 18, 2011 19:07
Show Gist options
  • Save dokterbob/876648 to your computer and use it in GitHub Desktop.
Save dokterbob/876648 to your computer and use it in GitHub Desktop.
Email field with domain existence validation for Django.
import logging
logger = logging.getLogger(__name__)
# Note: we need dnspython for this to work
# Install with `pip install dnspython`
import dns.resolver, dns.exception
from django import forms
from django.utils.translation import ugettext as _
class ValidatingEmailField(forms.EmailField):
"""
Django EmailField which checks for MX records on the email domain.
Requires dnspython to be installed.
"""
def clean(self, value):
email = super(ValidatingEmailField, self).clean(value)
domain = email.split('@')[1]
# Make sure the domain exists
try:
logger.debug('Checking domain %s', domain)
results = dns.resolver.query(domain, 'MX')
except dns.exception.DNSException, e:
logger.debug('Domain %s does not exist.', e)
raise \
forms.ValidationError(_(u"The domain %s could not be found.")
% domain)
return email
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment