[Fixed]-Django: How to check if something is an email without a form


You can use the following

from django.core.validators import validate_email
from django import forms

if request.method == "POST":
        validate_email(request.POST.get("email", ""))
    except forms.ValidationError:

assuming you have a <input type="text" name="email" /> in your form


You can use the validate_email() method from django.core.validators:

>>> from django.core import validators
>>> validators.validate_email('test@example.com')
>>> validators.validate_email('test@examplecom')
Traceback (most recent call last):
   File "<console>", line 1, in <module>
   File "/Users/jasper/Sites/iaid/env/lib/python2.7/site-    packages/django/core/validators.py", line 155, in __call__
    super(EmailValidator, self).__call__(u'@'.join(parts))
  File "/Users/jasper/Sites/iaid/env/lib/python2.7/site-packages/django/core/validators.py", line 44, in __call__
    raise ValidationError(self.message, code=self.code)
ValidationError: [u'Enter a valid e-mail address.']


import re

Using Python

def check_email(email) -> bool:
    # The regular expression
    pat = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b'
    if re.match(pat, email):
        return True
        return False

Using regular expression to validate the email

Using Django but this raise a validation error

from django.core import validators

Leave a comment