Skip to content

Instantly share code, notes, and snippets.

@mrmuxl
Forked from dokterbob/fields.py
Created March 21, 2013 12:58
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save mrmuxl/5212836 to your computer and use it in GitHub Desktop.
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