Class: HostnameValidator

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

Direct Known Subclasses

DomainnameValidator

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ HostnameValidator

Returns a new instance of HostnameValidator.



8
9
10
# File 'lib/valid_hostname/hostname_validator.rb', line 8

def initialize(options)
  super(ValidateHostname.default_options.merge(options))
end

Instance Method Details

#validate_each(record, attribute, value) ⇒ Object



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
41
42
43
44
45
46
47
48
# File 'lib/valid_hostname/hostname_validator.rb', line 12

def validate_each(record, attribute, value)
  value ||= ''

  if options[:verbose]
    add_error record, attribute, :invalid_hostname_length unless ValidateHostname.valid_length? value
    add_error record, attribute, :hostname_contains_consecutive_dots unless ValidateHostname.valid_dots? value

    unless ValidateHostname.valid_trailing_dot?(value,
                                                allow_root_label: options[:allow_root_label])
      add_error record, attribute, :hostname_ends_with_dot
    end

    unless ValidateHostname.valid_tld? value, valid_tlds: options[:valid_tlds], require_valid_tld: options[:require_valid_tld]
      add_error record, attribute, :hostname_is_not_fqdn
    end

    return unless value.is_a? String

    add_error record, attribute, :invalid_label_length unless ValidateHostname.valid_label_length? value
    add_error record, attribute, :label_begins_or_ends_with_hyphen unless ValidateHostname.valid_hyphens? value

    unless ValidateHostname.valid_characters?(value,
                                              allow_underscore: options[:allow_underscore],
                                              allow_wildcard_hostname: options[:allow_wildcard_hostname])
      add_error record,
                attribute,
                :label_contains_invalid_characters,
                valid_chars: ValidateHostname.allowed_characters(allow_underscore: options[:allow_underscore])
    end

    unless ValidateHostname.valid_numeric_only? value, allow_numeric_hostname: options[:allow_numeric_hostname]
      add_error record, attribute, :hostname_label_is_numeric
    end
  elsif !ValidateHostname.valid? value, **options
    record.errors.add attribute, options[:message].nil? ? I18n.t(:invalid, scope: 'activerecord.errors.messages') : options[:message]
  end
end