Class: HttpUrlValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
lib/app/validators/http_url_validator.rb

Overview

Validator for ensuring that an attribute contains a valid HTTP or HTTPS URL. Uses URI.parse to verify the scheme and the presence of a host.

Instance Method Summary collapse

Instance Method Details

#validate_each(record, attribute, value) ⇒ Object

Validates the format of the URL provided in the attribute.

Parameters:

  • record (ActiveModel::Model)

    The record being validated.

  • attribute (Symbol)

    The name of the attribute being validated.

  • value (Object)

    The value of the attribute to check.



10
11
12
13
14
15
16
17
18
19
# File 'lib/app/validators/http_url_validator.rb', line 10

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

  uri = URI.parse(value)
  return if uri.is_a?(URI::HTTP) && uri.host.present?

  record.errors.add(attribute, "is not a valid URL")
rescue URI::InvalidURIError
  record.errors.add(attribute, "is not a valid URL")
end