18

I have HTML form to post in Django View and because of some constraints, it's easier for me to do the validation without the usual Django form classes.

My only reason to use Django Forms is Email Field(s) that are entered.

Is there any function to check if something is an email or I have to use the EmailField to check and validate it?

Engineero
  • 12,340
  • 5
  • 53
  • 75
sinθ
  • 11,093
  • 25
  • 85
  • 121

3 Answers3

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

Timmy O'Mahony
  • 53,000
  • 18
  • 155
  • 177
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.']
Density 21.5
  • 1,955
  • 14
  • 17
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")
Codertjay
  • 588
  • 8
  • 13