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

37👍

You can use the following

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

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

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

6👍

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.']

0👍

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
    else:
        return False

Using regular expression to validate the email

Using Django but this raise a validation error

from django.core import validators
validators.validate_email("test@gmail.com")

Leave a comment