1

我想检测和过滤从表单发送的 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 text 中允许一个或各种 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,我该如何过滤?

4

3 回答 3

4

您可以使用 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
于 2013-04-26T13:50:52.240 回答
0

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

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

Nokogiri就是这样一个图书馆。

于 2013-04-26T10:53:27.543 回答
0

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

问候!

于 2013-04-26T14:28:42.780 回答