Class: ActiveModel::Validations::UrlValidator

Inherits:
EachValidator
  • Object
show all
Defined in:
lib/active_validators/active_model/validations/url_validator.rb

Overview

Public: Uses ‘URI.regexp` to validate URLs, by default only allows the http and https protocols.

Examples

validates :url, :url => true
# => only allow http, https

validates :url, :url => %w{http https ftp ftps}
# => allow http, https, ftp and ftps

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ UrlValidator

Public: Creates a new instance, overrides ‘:protocols` if either `:with` or `:in` are defined, to allow for shortcut setters.

Examples:

validates :url, :url => { :protocols => %w{http https ftp} }
# => accepts http, https and ftp URLs

validates :url, :url => 'https'
# => accepts only https URLs (shortcut form of above)

validates :url, :url => true
# => by default allows only http and https

Raises an ArgumentError if the array with the allowed protocols is empty.

Returns a new instance.



38
39
40
41
# File 'lib/active_validators/active_model/validations/url_validator.rb', line 38

def initialize(options)
  options[:protocols] ||= options.delete(:protocol) || options.delete(:with) || options.delete(:in)
  super
end

Instance Method Details

#validate_each(record, attribute, value) ⇒ Object

Public: Validate URL, if it fails adds an error.

Returns nothing.



46
47
48
49
50
# File 'lib/active_validators/active_model/validations/url_validator.rb', line 46

def validate_each(record, attribute, value)
  uri = as_uri(value)
  tld_requirement_fullfilled = check_tld_requirement(value)
  record.errors.add(attribute) unless uri && value.to_s =~ uri_regexp && tld_requirement_fullfilled
end