Advertisement
Guest User

Untitled

a guest
Jul 17th, 2018
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 7.85 KB | None | 0 0
  1. http://invalid##host.com
  2.  
  3. http://invalid-host.foo
  4.  
  5. http://host.foo
  6.  
  7. http://localhost
  8.  
  9. require 'uri'
  10.  
  11. def valid_url?(uri)
  12. uri = URI.parse(uri) && !uri.host.nil?
  13. rescue URI::InvalidURIError
  14. false
  15. end
  16.  
  17. require 'uri'
  18.  
  19. def valid_url?(url)
  20. uri = URI.parse(url)
  21. uri.is_a?(URI::HTTP) && !uri.host.nil?
  22. rescue URI::InvalidURIError
  23. false
  24. end
  25.  
  26. class HttpUrlValidator < ActiveModel::EachValidator
  27.  
  28. def self.compliant?(value)
  29. uri = URI.parse(value)
  30. uri.is_a?(URI::HTTP) && !uri.host.nil?
  31. rescue URI::InvalidURIError
  32. false
  33. end
  34.  
  35. def validate_each(record, attribute, value)
  36. unless value.present? && self.class.compliant?(value)
  37. record.errors.add(attribute, "is not a valid HTTP URL")
  38. end
  39. end
  40.  
  41. end
  42.  
  43. # in the model
  44. validates :example_attribute, http_url: true
  45.  
  46. class UrlValidator < ActiveModel::EachValidator
  47. def validate_each(record, attribute, value)
  48. return if value.blank?
  49. begin
  50. uri = URI.parse(value)
  51. resp = uri.kind_of?(URI::HTTP)
  52. rescue URI::InvalidURIError
  53. resp = false
  54. end
  55. unless resp == true
  56. record.errors[attribute] << (options[:message] || "is not an url")
  57. end
  58. end
  59. end
  60.  
  61. validates :url, :presence => true, :url => true
  62.  
  63. # app/models/my_model.rb
  64. validates :website, :allow_blank => true, :uri => { :format => /(^$)|(^(http|https)://[a-z0-9]+([-.]{1}[a-z0-9]+)*.[a-z]{2,5}(([0-9]{1,5})?/.*)?$)/ix }
  65.  
  66. def website= url_str
  67. unless url_str.blank?
  68. unless url_str.split(':')[0] == 'http' || url_str.split(':')[0] == 'https'
  69. url_str = "http://" + url_str
  70. end
  71. end
  72. write_attribute :website, url_str
  73. end
  74.  
  75. # app/validators/uri_vaidator.rb
  76. require 'net/http'
  77.  
  78. # Thanks Ilya! http://www.igvita.com/2006/09/07/validating-url-in-ruby-on-rails/
  79. # Original credits: http://blog.inquirylabs.com/2006/04/13/simple-uri-validation/
  80. # HTTP Codes: http://www.ruby-doc.org/stdlib/libdoc/net/http/rdoc/classes/Net/HTTPResponse.html
  81.  
  82. class UriValidator < ActiveModel::EachValidator
  83. def validate_each(object, attribute, value)
  84. raise(ArgumentError, "A regular expression must be supplied as the :format option of the options hash") unless options[:format].nil? or options[:format].is_a?(Regexp)
  85. configuration = { :message => I18n.t('errors.events.invalid_url'), :format => URI::regexp(%w(http https)) }
  86. configuration.update(options)
  87.  
  88. if value =~ configuration[:format]
  89. begin # check header response
  90. case Net::HTTP.get_response(URI.parse(value))
  91. when Net::HTTPSuccess then true
  92. else object.errors.add(attribute, configuration[:message]) and false
  93. end
  94. rescue # Recover on DNS failures..
  95. object.errors.add(attribute, configuration[:message]) and false
  96. end
  97. else
  98. object.errors.add(attribute, configuration[:message]) and false
  99. end
  100. end
  101. end
  102.  
  103. class WebSite < ActiveRecord::Base
  104. validates :url, :url => true
  105. end
  106.  
  107. before_validation :format_website
  108. validate :website_validator
  109.  
  110. private
  111.  
  112. def format_website
  113. self.website = "http://#{self.website}" unless self.website[/^https?/]
  114. end
  115.  
  116. def website_validator
  117. errors[:website] << I18n.t("activerecord.errors.messages.invalid") unless website_valid?
  118. end
  119.  
  120. def website_valid?
  121. !!website.match(/^(https?://)?([da-z.-]+).([a-z.]{2,6})([/w .-=?]*)*/?$/)
  122. end
  123.  
  124. validates_format_of :url, :with => /A(https?://)?([da-z.-]+).([a-z.]{2,6})([/w.-]*)*/?Z/i
  125.  
  126. Valid ones:
  127. 'www.crowdint.com'
  128. 'crowdint.com'
  129. 'http://crowdint.com'
  130. 'http://www.crowdint.com'
  131.  
  132. Invalid ones:
  133. 'http://www.crowdint. com'
  134. 'http://fake'
  135. 'http:fake'
  136.  
  137. require 'addressable/uri'
  138.  
  139. # Source: http://gist.github.com/bf4/5320847
  140. # Accepts options[:message] and options[:allowed_protocols]
  141. # spec/validators/uri_validator_spec.rb
  142. class UriValidator < ActiveModel::EachValidator
  143.  
  144. def validate_each(record, attribute, value)
  145. uri = parse_uri(value)
  146. if !uri
  147. record.errors[attribute] << generic_failure_message
  148. elsif !allowed_protocols.include?(uri.scheme)
  149. record.errors[attribute] << "must begin with #{allowed_protocols_humanized}"
  150. end
  151. end
  152.  
  153. private
  154.  
  155. def generic_failure_message
  156. options[:message] || "is an invalid URL"
  157. end
  158.  
  159. def allowed_protocols_humanized
  160. allowed_protocols.to_sentence(:two_words_connector => ' or ')
  161. end
  162.  
  163. def allowed_protocols
  164. @allowed_protocols ||= [(options[:allowed_protocols] || ['http', 'https'])].flatten
  165. end
  166.  
  167. def parse_uri(value)
  168. uri = Addressable::URI.parse(value)
  169. uri.scheme && uri.host && uri
  170. rescue URI::InvalidURIError, Addressable::URI::InvalidURIError, TypeError
  171. end
  172.  
  173. end
  174.  
  175. require 'spec_helper'
  176.  
  177. # Source: http://gist.github.com/bf4/5320847
  178. # spec/validators/uri_validator_spec.rb
  179. describe UriValidator do
  180. subject do
  181. Class.new do
  182. include ActiveModel::Validations
  183. attr_accessor :url
  184. validates :url, uri: true
  185. end.new
  186. end
  187.  
  188. it "should be valid for a valid http url" do
  189. subject.url = 'http://www.google.com'
  190. subject.valid?
  191. subject.errors.full_messages.should == []
  192. end
  193.  
  194. ['http://google', 'http://.com', 'http://ftp://ftp.google.com', 'http://ssh://google.com'].each do |invalid_url|
  195. it "#{invalid_url.inspect} is a invalid http url" do
  196. subject.url = invalid_url
  197. subject.valid?
  198. subject.errors.full_messages.should == []
  199. end
  200. end
  201.  
  202. ['http:/www.google.com','<>hi'].each do |invalid_url|
  203. it "#{invalid_url.inspect} is an invalid url" do
  204. subject.url = invalid_url
  205. subject.valid?
  206. subject.errors.should have_key(:url)
  207. subject.errors[:url].should include("is an invalid URL")
  208. end
  209. end
  210.  
  211. ['www.google.com','google.com'].each do |invalid_url|
  212. it "#{invalid_url.inspect} is an invalid url" do
  213. subject.url = invalid_url
  214. subject.valid?
  215. subject.errors.should have_key(:url)
  216. subject.errors[:url].should include("is an invalid URL")
  217. end
  218. end
  219.  
  220. ['ftp://ftp.google.com','ssh://google.com'].each do |invalid_url|
  221. it "#{invalid_url.inspect} is an invalid url" do
  222. subject.url = invalid_url
  223. subject.valid?
  224. subject.errors.should have_key(:url)
  225. subject.errors[:url].should include("must begin with http or https")
  226. end
  227. end
  228. end
  229.  
  230. http://google
  231. http://.com
  232. http://ftp://ftp.google.com
  233. http://ssh://google.com
  234.  
  235. %r"A(https?://)?[a-zd-]+(.[a-zd-]+)*.[a-z]{2,6}(/.*)?Z"i
  236.  
  237. # Activate all the validators
  238. ActiveValidators.activate(:all)
  239.  
  240. class Url < ActiveRecord::Base
  241. validates :url, :presence => true, :url => true
  242. end
  243.  
  244. validates_format_of [:field1, :field2], with: URI.regexp(['http', 'https']), allow_nil: true
  245.  
  246. validates_format_of :url, :with => URI::regexp(%w(http https))
  247. validate :validate_url
  248. def validate_url
  249.  
  250. unless self.url.blank?
  251.  
  252. begin
  253.  
  254. source = URI.parse(self.url)
  255.  
  256. resp = Net::HTTP.get_response(source)
  257.  
  258. rescue URI::InvalidURIError
  259.  
  260. errors.add(:url,'is Invalid')
  261.  
  262. rescue SocketError
  263.  
  264. errors.add(:url,'is Invalid')
  265.  
  266. end
  267.  
  268.  
  269.  
  270. end
  271.  
  272. module UrlValidator
  273. extend ActiveSupport::Concern
  274. included do
  275. validates :url, presence: true, uniqueness: true
  276. validate :url_format
  277. end
  278.  
  279. def url_format
  280. begin
  281. errors.add(:url, "Invalid url") unless URI(self.url).is_a?(URI::HTTP)
  282. rescue URI::InvalidURIError
  283. errors.add(:url, "Invalid url")
  284. end
  285. end
  286. end
  287.  
  288. class UrlValidator < ActiveModel::Validator
  289. def validate(record)
  290. begin
  291. url = URI.parse(record.path)
  292. response = Net::HTTP.get(url)
  293. true if response.is_a?(Net::HTTPSuccess)
  294. rescue StandardError => error
  295. record.errors[:path] << 'Web address is invalid'
  296. false
  297. end
  298. end
  299. end
  300.  
  301. class Url < ApplicationRecord
  302.  
  303. # validations
  304. validates_presence_of :path
  305. validates_with UrlValidator
  306.  
  307. end
  308.  
  309. (^|[s.:;?-]<(])(ftp|https?://[-w;/?:@&=+$|_.!~*|'()[]%#,]+[w/#](())?)(?=$|[s',|().:;?-[]>)])
  310.  
  311. validates :some_field_expecting_url_value,
  312. format: {
  313. with: URI.regexp(%w[http https]),
  314. message: 'is not a valid URL'
  315. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement