【问题标题】:validate presence of url in html text验证 html 文本中是否存在 url
【发布时间】:2013-04-20 12:28:54
【问题描述】:

我想检测和过滤从表单发送的 html 文本是否包含 url 或 url。

例如,我从一个表单发送这个 html:

RESOURCES<br></u></b><a target="_blank" rel="nofollow" href="http://stackoverflow.com/users/778094/hyperrjas">http://stackoverflow.com/users/778094/hyperrjas</a>&nbsp;<br><a target="_blank" rel="nofollow" href="https://github.com/hyperrjas">https://github.com/hyperrjas</a>&nbsp;<br><a target="_blank" rel="nofollow" href="http://www.linkedin.com/pub/juan-ardila-serrano/11/2a7/62">http://www.linkedin.com/pub/juan-ardila-serrano/11/2a7/62</a>&nbsp;<br>

我不想在 html 文本中允许一个或多个 url/urls。可能是这样的:

validate :no_urls

def no_urls
  if text_contains_url
   errors.add(:url, "#{I18n.t("mongoid.errors.models.profile.attributes.url.urls_are_not_allowed_in_this_text", url: url)}")
  end
end

我想知道,如果html文本包含一个或多个url,我该如何过滤?

【问题讨论】:

    标签: ruby-on-rails ruby regex ruby-on-rails-3 ruby-on-rails-3.2


    【解决方案1】:

    您可以使用 Ruby 内置的 URI 模块,该模块已经可以从文本中提取 URI。

    require "uri"
    
    links = URI.extract("your text goes here http://example.com mailto:test@example.com foo bar and more...")
    links => ["http://example.com", "mailto:test@example.com"]
    

    所以你可以像下面这样修改你的验证:

    validate :no_html
    
    def no_html(text)
      links = URI.extract(text)
      unless links.empty?
        errors.add(:url, "#{I18n.t("mongoid.errors.models.profile.attributes.url.urls_are_not_allowed_in_this_text", url: url)}")
      end
    end
    

    【讨论】:

      【解决方案2】:

      您可以使用正则表达式来解析看起来像 url 的字符串,例如像这样:/^http:\/\/.*/

      但是如果你想检测像a这样的html标签,你应该查看用于解析html的库。

      Nokogiri 就是这样一个库。

      【讨论】:

        【解决方案3】:

        只有当字符串不包含冒号 ":" 时,Matherick 的答案才有效。

        对于 Ruby 1.9.3,正确的做法是添加第二个参数来解决此问题。

        此外,如果您将电子邮件地址添加为纯文本,则此代码不会过滤此电子邮件地址。这个问题的解决方法是:

        html_text  = "html text with email address e.g. info@test.com"
        email_address = html_text.match(/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}/i)[0]
        

        所以,这是我的代码,适合我:

        def no_urls
          whitelist = %w(attr1, attr2, attr3, attr4)
          attributes.select{|el| whitelist.include?(el)}.each do |key, value|
            links = URI.extract(value, /http(s)?|mailto/)
            email_address = "#{value.match(/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}/i)}"
            unless links.empty? and email_address.empty?
              logger.info links.first.inspect
              errors.add(key, "#{I18n.t("mongoid.errors.models.cv.attributes.no_urls")}")
            end
          end
        end
        

        问候!

        【讨论】:

          猜你喜欢
          • 2022-11-10
          • 1970-01-01
          • 1970-01-01
          • 2010-11-28
          • 1970-01-01
          • 2023-04-08
          • 1970-01-01
          • 2021-07-23
          • 1970-01-01
          相关资源
          最近更新 更多