我已经写了一个功能,添加电子邮件到时事通讯基地。在我添加了检查发送电子邮件的有效性之前,它的工作是完美无缺的。现在每次我收到“错误的电子邮件”作为回报。有人看到这里有什么错误吗?使用的regex是:
\b[\w\.-]+@[\w\.-]+\.\w{2,4}\b
并且它是100%有效的(http://gskinner.com/RegExr/),但是我可能使用错误,或者可能是一些逻辑错误:
def newsletter_add(request):
if request.method == "POST":
try:
e = NewsletterEmails.objects.get(email = request.POST['email'])
message = _(u"Email is already added.")
type = "error"
except NewsletterEmails.DoesNotExist:
if validateEmail(request.POST['email']):
try:
e = NewsletterEmails(email = request.POST['email'])
except DoesNotExist:
pass
message = _(u"Email added.")
type = "success"
e.save()
else:
message = _(u"Wrong email")
type = "error"
import re
def validateEmail(email):
if len(email) > 6:
if re.match('\b[\w\.-]+@[\w\.-]+\.\w{2,4}\b', email) != None:
return 1
return 0
这是django.core.validators的一部分,您可能会发现它很有趣:)
因此,如果不想使用表单和表单域,可以导入
email_re
并在函数中使用它,或者更好的方法是导入validate_email
并使用它,捕获可能的ValidationError
。这里是PERL中使用的Mail::RFC822::Address regexp,如果您真的需要那么多疑的话。
Ick,不,请不要自己验证电子邮件地址。这是人们永远不会做对的事情之一。
既然您已经在使用Django,那么您最安全的选择就是利用它对电子邮件的表单验证。根据文档(http://docs.djangoproject.com/en/dev/ref/forms/fields/):
相关问题 更多 >
编程相关推荐