-
-
Save diogosimao/ba82634b5669dcd6fdb54f514f515bc1 to your computer and use it in GitHub Desktop.
Email field with domain existence validation for Django.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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