Class: ActiveModel::Validations::UrlValidator

Inherits:
EachValidator
  • Object
show all
Defined in:
lib/validators/validates_url_format_of.rb

Instance Method Summary collapse

Instance Method Details

#url?(url) ⇒ Boolean

Returns:

  • (Boolean)


15
16
17
18
19
20
21
22
23
24
25
# File 'lib/validators/validates_url_format_of.rb', line 15

def url?(url)
  uri = URI(url)
  regex = options[:tld] ? Validators::URL_FORMAT_WITHOUT_TLD_VALIDATION :
                          Validators::URL_FORMAT

  uri.kind_of?(URI::HTTP) &&
  url.match(regex) &&
  valid_tld?(uri.host)
rescue URI::InvalidURIError
  false
end

#valid_tld?(host) ⇒ Boolean

Returns:

  • (Boolean)


27
28
29
30
# File 'lib/validators/validates_url_format_of.rb', line 27

def valid_tld?(host)
  return true unless options[:tld]
  Validators::TLD.host_with_valid_tld?(host)
end

#validate_each(record, attribute, value) ⇒ Object



4
5
6
7
8
9
10
11
12
13
# File 'lib/validators/validates_url_format_of.rb', line 4

def validate_each(record, attribute, value)
  return if value.blank? && options[:allow_blank]
  return if value.nil? && options[:allow_nil]
  return if url?(value.to_s)

  record.errors.add(attribute, :invalid_url,
    :message => options[:message],
    :value => value
  )
end