Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: How to check if something is an email without a form

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?

like image 697
sinθ Avatar asked Dec 21 '12 20:12

sinθ


People also ask

How do I check if a email is valid in Django?

Just use isEmailAddressValid(address) to perform the validation. Since the question is about Django, this is the best answer.

How do I check if a form is valid in Django?

The is_valid() method is used to perform validation for each field of the form, it is defined in Django Form class. It returns True if data is valid and place all data into a cleaned_data attribute. Let's see an example that takes user input and validate input as well.


2 Answers

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

like image 121
Timmy O'Mahony Avatar answered Sep 17 '22 15:09

Timmy O'Mahony


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

>>> from django.core import validators
>>> validators.validate_email('[email protected]')
>>> 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.']
like image 27
Density 21.5 Avatar answered Sep 18 '22 15:09

Density 21.5