Module: ValidateAsUrl

Defined in:
lib/validate_as_url.rb

Defined Under Namespace

Modules: Validations

Constant Summary collapse

MessageScope =

require ‘resolv’

defined?(ActiveModel) ? :activemodel : :activerecord

Class Method Summary collapse

Class Method Details

.validate_as_url(url, options = {}) ⇒ Object

LocalPartSpecialChars = /[!#$%&'*-/=?+-^_`{|}~]/



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/validate_as_url.rb', line 9

def self.validate_as_url(url, options={})
	options ||={}

	default_options = {
		message_invalid: ::I18n.t(:invalid_url, :scope => [MessageScope, :errors, :messages], :default => 'does not appear to be valid url'),
		message_nil:  ::I18n.t(:invalid_url, :scope => [MessageScope, :errors, :messages], :default => 'cannot be null'),
		message_blank: ::I18n.t(:invalid_url, :scope => [MessageScope, :errors, :messages], :default => 'cannot be blank'),
		allow_nil: false,
		allow_blank: false
	}
	opts = options.merge(default_options) # merge the default options into the specified options, retaining all specified options

	if opts[:allow_nil] == false
		if url.nil?
			return [ opts[:message_nil] ]
		end
	end

	url = url.to_s.strip

	if opts[:allow_blank] == false
		if url.blank?
			return [ opts[:message_blank] ]
		end
	end

	unless url =~ /^(http|https):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(([0-9]{1,5})?\/.*)?$/ix
		return [ opts[:message_invalid] ]
	end

	return nil    # represents no validation errors
end