Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- http://invalid##host.com
- http://invalid-host.foo
- http://host.foo
- http://localhost
- require 'uri'
- def valid_url?(uri)
- uri = URI.parse(uri) && !uri.host.nil?
- rescue URI::InvalidURIError
- false
- end
- require 'uri'
- def valid_url?(url)
- uri = URI.parse(url)
- uri.is_a?(URI::HTTP) && !uri.host.nil?
- rescue URI::InvalidURIError
- false
- end
- class HttpUrlValidator < ActiveModel::EachValidator
- def self.compliant?(value)
- uri = URI.parse(value)
- uri.is_a?(URI::HTTP) && !uri.host.nil?
- rescue URI::InvalidURIError
- false
- end
- def validate_each(record, attribute, value)
- unless value.present? && self.class.compliant?(value)
- record.errors.add(attribute, "is not a valid HTTP URL")
- end
- end
- end
- # in the model
- validates :example_attribute, http_url: true
- class UrlValidator < ActiveModel::EachValidator
- def validate_each(record, attribute, value)
- return if value.blank?
- begin
- uri = URI.parse(value)
- resp = uri.kind_of?(URI::HTTP)
- rescue URI::InvalidURIError
- resp = false
- end
- unless resp == true
- record.errors[attribute] << (options[:message] || "is not an url")
- end
- end
- end
- validates :url, :presence => true, :url => true
- # app/models/my_model.rb
- 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 }
- def website= url_str
- unless url_str.blank?
- unless url_str.split(':')[0] == 'http' || url_str.split(':')[0] == 'https'
- url_str = "http://" + url_str
- end
- end
- write_attribute :website, url_str
- end
- # app/validators/uri_vaidator.rb
- require 'net/http'
- # Thanks Ilya! http://www.igvita.com/2006/09/07/validating-url-in-ruby-on-rails/
- # Original credits: http://blog.inquirylabs.com/2006/04/13/simple-uri-validation/
- # HTTP Codes: http://www.ruby-doc.org/stdlib/libdoc/net/http/rdoc/classes/Net/HTTPResponse.html
- class UriValidator < ActiveModel::EachValidator
- def validate_each(object, attribute, value)
- 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)
- configuration = { :message => I18n.t('errors.events.invalid_url'), :format => URI::regexp(%w(http https)) }
- configuration.update(options)
- if value =~ configuration[:format]
- begin # check header response
- case Net::HTTP.get_response(URI.parse(value))
- when Net::HTTPSuccess then true
- else object.errors.add(attribute, configuration[:message]) and false
- end
- rescue # Recover on DNS failures..
- object.errors.add(attribute, configuration[:message]) and false
- end
- else
- object.errors.add(attribute, configuration[:message]) and false
- end
- end
- end
- class WebSite < ActiveRecord::Base
- validates :url, :url => true
- end
- before_validation :format_website
- validate :website_validator
- private
- def format_website
- self.website = "http://#{self.website}" unless self.website[/^https?/]
- end
- def website_validator
- errors[:website] << I18n.t("activerecord.errors.messages.invalid") unless website_valid?
- end
- def website_valid?
- !!website.match(/^(https?://)?([da-z.-]+).([a-z.]{2,6})([/w .-=?]*)*/?$/)
- end
- validates_format_of :url, :with => /A(https?://)?([da-z.-]+).([a-z.]{2,6})([/w.-]*)*/?Z/i
- Valid ones:
- 'www.crowdint.com'
- 'crowdint.com'
- 'http://crowdint.com'
- 'http://www.crowdint.com'
- Invalid ones:
- 'http://www.crowdint. com'
- 'http://fake'
- 'http:fake'
- require 'addressable/uri'
- # Source: http://gist.github.com/bf4/5320847
- # Accepts options[:message] and options[:allowed_protocols]
- # spec/validators/uri_validator_spec.rb
- class UriValidator < ActiveModel::EachValidator
- def validate_each(record, attribute, value)
- uri = parse_uri(value)
- if !uri
- record.errors[attribute] << generic_failure_message
- elsif !allowed_protocols.include?(uri.scheme)
- record.errors[attribute] << "must begin with #{allowed_protocols_humanized}"
- end
- end
- private
- def generic_failure_message
- options[:message] || "is an invalid URL"
- end
- def allowed_protocols_humanized
- allowed_protocols.to_sentence(:two_words_connector => ' or ')
- end
- def allowed_protocols
- @allowed_protocols ||= [(options[:allowed_protocols] || ['http', 'https'])].flatten
- end
- def parse_uri(value)
- uri = Addressable::URI.parse(value)
- uri.scheme && uri.host && uri
- rescue URI::InvalidURIError, Addressable::URI::InvalidURIError, TypeError
- end
- end
- require 'spec_helper'
- # Source: http://gist.github.com/bf4/5320847
- # spec/validators/uri_validator_spec.rb
- describe UriValidator do
- subject do
- Class.new do
- include ActiveModel::Validations
- attr_accessor :url
- validates :url, uri: true
- end.new
- end
- it "should be valid for a valid http url" do
- subject.url = 'http://www.google.com'
- subject.valid?
- subject.errors.full_messages.should == []
- end
- ['http://google', 'http://.com', 'http://ftp://ftp.google.com', 'http://ssh://google.com'].each do |invalid_url|
- it "#{invalid_url.inspect} is a invalid http url" do
- subject.url = invalid_url
- subject.valid?
- subject.errors.full_messages.should == []
- end
- end
- ['http:/www.google.com','<>hi'].each do |invalid_url|
- it "#{invalid_url.inspect} is an invalid url" do
- subject.url = invalid_url
- subject.valid?
- subject.errors.should have_key(:url)
- subject.errors[:url].should include("is an invalid URL")
- end
- end
- ['www.google.com','google.com'].each do |invalid_url|
- it "#{invalid_url.inspect} is an invalid url" do
- subject.url = invalid_url
- subject.valid?
- subject.errors.should have_key(:url)
- subject.errors[:url].should include("is an invalid URL")
- end
- end
- ['ftp://ftp.google.com','ssh://google.com'].each do |invalid_url|
- it "#{invalid_url.inspect} is an invalid url" do
- subject.url = invalid_url
- subject.valid?
- subject.errors.should have_key(:url)
- subject.errors[:url].should include("must begin with http or https")
- end
- end
- end
- http://google
- http://.com
- http://ftp://ftp.google.com
- http://ssh://google.com
- %r"A(https?://)?[a-zd-]+(.[a-zd-]+)*.[a-z]{2,6}(/.*)?Z"i
- # Activate all the validators
- ActiveValidators.activate(:all)
- class Url < ActiveRecord::Base
- validates :url, :presence => true, :url => true
- end
- validates_format_of [:field1, :field2], with: URI.regexp(['http', 'https']), allow_nil: true
- validates_format_of :url, :with => URI::regexp(%w(http https))
- validate :validate_url
- def validate_url
- unless self.url.blank?
- begin
- source = URI.parse(self.url)
- resp = Net::HTTP.get_response(source)
- rescue URI::InvalidURIError
- errors.add(:url,'is Invalid')
- rescue SocketError
- errors.add(:url,'is Invalid')
- end
- end
- module UrlValidator
- extend ActiveSupport::Concern
- included do
- validates :url, presence: true, uniqueness: true
- validate :url_format
- end
- def url_format
- begin
- errors.add(:url, "Invalid url") unless URI(self.url).is_a?(URI::HTTP)
- rescue URI::InvalidURIError
- errors.add(:url, "Invalid url")
- end
- end
- end
- class UrlValidator < ActiveModel::Validator
- def validate(record)
- begin
- url = URI.parse(record.path)
- response = Net::HTTP.get(url)
- true if response.is_a?(Net::HTTPSuccess)
- rescue StandardError => error
- record.errors[:path] << 'Web address is invalid'
- false
- end
- end
- end
- class Url < ApplicationRecord
- # validations
- validates_presence_of :path
- validates_with UrlValidator
- end
- (^|[s.:;?-]<(])(ftp|https?://[-w;/?:@&=+$|_.!~*|'()[]%#,]+[w/#](())?)(?=$|[s',|().:;?-[]>)])
- validates :some_field_expecting_url_value,
- format: {
- with: URI.regexp(%w[http https]),
- message: 'is not a valid URL'
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement