Class: ActiveModel::Validations::HostnameValidator

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

Instance Method Summary collapse

Instance Method Details

#valid_hostname?(host) ⇒ Boolean

Returns:

  • (Boolean)


16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/validators/validates_hostname_format_of.rb', line 16

def valid_hostname?(host)
  host = host.to_s
  uri = URI(host)

  host.present? &&
  uri.host.nil? &&
  uri.scheme.nil? &&
  uri.fragment.nil? &&
  uri.query.nil? &&
  uri.path == host &&
  host.split('.').all? {|label| valid_label?(label) } &&
  host.size <= 255 &&
  valid_tld?(host)
rescue URI::InvalidURIError
  false
end

#valid_label?(label) ⇒ Boolean

Returns:

  • (Boolean)


33
34
35
36
37
# File 'lib/validators/validates_hostname_format_of.rb', line 33

def valid_label?(label)
  !label.start_with?('-') &&
  !label.match(/\A\d+\z/) &&
  label.match(/\A[a-z0-9-]{1,63}\z/i)
end

#valid_tld?(host) ⇒ Boolean

Returns:

  • (Boolean)


39
40
41
42
# File 'lib/validators/validates_hostname_format_of.rb', line 39

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

#validate_each(record, attribute, value) ⇒ Object



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

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

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