Class: DomainValidator

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

Overview

DomainValidator is a custom ActiveModel validator for URL/domain validation.

This validator is defined at the top level so Rails can find it when using:

validates :url, domain: { validation: :standard }

Validation modes:

  • :standard - Validates any valid URL using DomainExtractor.valid?

  • :root_domain - Only allows root domains (no subdomains) like mysite.com

  • :root_or_custom_subdomain - Allows root or custom subdomains but excludes ‘www’

Optional flags:

  • use_protocol (default: true) - Whether protocol (http/https) is required

  • use_https (default: true) - Whether https is required (only if use_protocol is true)

Examples:

Standard validation

validates :url, domain: { validation: :standard }

Root domain only, no protocol required

validates :url, domain: { validation: :root_domain, use_protocol: false }

Root or custom subdomain with https required

validates :url, domain: { validation: :root_or_custom_subdomain, use_https: true }

Constant Summary collapse

VALIDATION_MODES =
i[standard root_domain root_or_custom_subdomain].freeze
WWW_SUBDOMAIN =
'www'

Instance Method Summary collapse

Instance Method Details

#validate_each(record, attribute, value) ⇒ Object



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/domain_extractor/domain_validator.rb', line 45

def validate_each(record, attribute, value)
  return if blank?(value)

  validation_mode = extract_validation_mode
  use_protocol = options.fetch(:use_protocol, true)
  use_https = options.fetch(:use_https, true)

  normalized_url = normalize_url(value, use_protocol, use_https)

  return unless protocol_valid?(record, attribute, normalized_url, use_protocol, use_https)

  parsed = parse_and_validate_url(record, attribute, normalized_url)
  return unless parsed

  apply_validation_mode(record, attribute, parsed, validation_mode)
end