【问题标题】:How to validate a form not to accept 'http' or 'https' in message body? [duplicate]如何验证表单不接受消息正文中的“http”或“https”? [复制]
【发布时间】:2019-05-03 22:43:24
【问题描述】:

我尝试使用 django 的 regexvalidators 来验证表单,使其不包含 http 或 https(许多垃圾邮件发送者使用链接),但它不起作用。

from django import forms
from django.core.validators import RegexValidator
from antispam.honeypot.forms import HoneypotField

class ContactForm(forms.Form):
    name = forms.CharField(max_length=50)
    email = forms.EmailField()
    phone = forms.CharField(max_length=11)
    message = forms.CharField(widget=forms.Textarea, validators=[RegexValidator(regex=r'http(s)?|HTTP(s)?', message="I don't accept link", code="invalid")])
    spam_honeypot_field = HoneypotField()

我该如何解决这个问题?

【问题讨论】:

    标签: python regex django validation


    【解决方案1】:

    This expression 可能会帮助您这样做:

    ^((?!http|https).)+$
    

    根据Pushpesh 的建议,您可以使用带有负前瞻的much simplified expression

    ^(?!.*\bhttps?\b).+$
    

    这张图显示了它是如何工作的:

    代码

    import re
    
    string = 'Anything else that you wish except http://someurl.org'
    # string = 'Anything else that you wish'
    matches = re.search(r'^(((?!http|https).)+)$', string)
    if matches:
        print(matches.group(1)+ " is a match")
    else: 
        print('Sorry! No matches! Something is not right! Call 911!')
    

    输出

    Sorry! No matches! Something is not right! Call 911!
    

    【讨论】:

    • 请问为什么第 3 行与您的正则表达式不匹配?
    • 酷...+1 来自我 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-04
    • 1970-01-01
    • 2014-06-22
    • 2018-05-30
    • 2014-07-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多