1

양식에서 보낸 HTML 텍스트에 url 또는 urls가 포함되어 있는지 검색하고 필터링하고 싶습니다.html 텍스트에 url 존재 여부 확인

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/URL을 허용하지 않습니다

예를 들어, 내가 양식에서이 HTML을 보낼 수 있습니다. 이 같은 수 : html로 텍스트가 각종 URL을 포함하는 경우 내가 알고 싶습니다

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 

을, 어떻게 필터링 할 수 있습니다?

답변

0

을 문자열이 아닌 콜론 기호 포함 된 경우 ":"합니다.

루비 1.9.3 올바른 것은이 문제를 해결하기위한 두 번째 매개 변수를 추가하는 것입니다.

또한 이메일 주소를 일반 텍스트로 추가하면이 코드는이 이메일 주소를 필터링하지 않습니다. 이 문제에 대한 수정 프로그램은 다음과 같습니다

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._%+-][email protected][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 

감사 : 그래서

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

이 나를 위해 올바르게 작동 내 코드입니다!

0

URL과 같이 보이는 문자열을 정규식을 사용하여 구문 분석 할 수 있습니다. 예 : /^http:\/\/.*/

a과 같은 html 태그를 검색하려면 html 구문 분석을위한 라이브러리를 조사해야합니다.

Nokogiri은 이러한 라이브러리 중 하나입니다.

4

이미 텍스트에서 URI를 추출 할 수있는 URI 모듈에서 Ruby를 빌드 할 수 있습니다.

require "uri" 

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

그래서 당신은 다음과 같이 유효성 검사를 수정할 수 다음 Mattherick의 대답은 작동

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