Class: HostnameValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
lib/validates_hostname.rb

Overview

Validates hostnames.

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ HostnameValidator

Returns a new instance of HostnameValidator.

Parameters:

  • options (Hash)

Options Hash (options):

  • :allow_underscore (Boolean) — default: false

    Allows underscores in hostname labels.

  • :require_valid_tld (Boolean) — default: false

    Requires the hostname to have a valid TLD.

  • :valid_tlds (Array<String>) — default: ALLOWED_TLDS

    A list of valid TLDs.

  • :allow_numeric_hostname (Boolean) — default: false

    Allows numeric-only hostname labels.

  • :allow_wildcard_hostname (Boolean) — default: false

    Allows wildcard hostnames.

  • :allow_root_label (Boolean) — default: false

    Allows a trailing dot.



37
38
39
40
41
42
43
44
45
46
# File 'lib/validates_hostname.rb', line 37

def initialize(options)
  super({
    allow_underscore: false,
    require_valid_tld: false,
    valid_tlds: ALLOWED_TLDS,
    allow_numeric_hostname: false,
    allow_wildcard_hostname: false,
    allow_root_label: false
  }.merge(options))
end

Instance Method Details

#validate_each(record, attribute, value) ⇒ Object

Validates the hostname.

Parameters:

  • record (ActiveModel::Base)

    The record to validate.

  • attribute (Symbol)

    The attribute to validate.

  • value (String)

    The value to validate.



53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/validates_hostname.rb', line 53

def validate_each(record, attribute, value)
  value = value.to_s
  labels = value.split('.')

  validate_hostname_length(record, attribute, value)
  # CHECK 1: hostname label cannot be longer than 63 characters
  validate_label_length(record, attribute, labels)
  # CHECK 2: hostname label cannot begin or end with hyphen
  validate_label_hyphens(record, attribute, labels)
  # CHECK 3: hostname can only contain valid characters
  validate_label_characters(record, attribute, labels)
  # CHECK 4: the unqualified hostname portion cannot consist of numeric values only
  validate_numeric_hostname(record, attribute, labels)
  # CHECK 5: TLD must be valid if required
  handle_tld_validation(record, attribute, value, labels)
  # CHECK 6: hostname may not contain consecutive dots
  validate_consecutive_dots(record, attribute, value)
  # CHECK 7: do not allow trailing dot unless option is set
  validate_trailing_dot(record, attribute, value)
end