我有HTML表单在Django View中发布,由于一些限制,我更容易在没有通常的Django表单类的情况下执行validation
。
我使用Django Forms的唯一理由是输入的电子邮件字段。
是否有任何功能可以检查某些内容是email
还是我必须使用EmailField
进行检查和验证?
答案 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.']