Django:如何检查某些内容是否是没有表单的电子邮件

时间:2012-12-21 20:12:48

标签: python django emailfield

我有HTML表单在Django View中发布,由于一些限制,我更容易在没有通常的Django表单类的情况下执行validation

我使用Django Forms的唯一理由是输入的电子邮件字段。

是否有任何功能可以检查某些内容是email还是我必须使用EmailField进行检查和验证?

2 个答案:

答案 0 :(得分:27)

您可以使用以下

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:
        ...

假设您的表单中有<input type="text" name="email" />

答案 1 :(得分:5)

您可以使用django.core.validators中的validate_email()方法:

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