Class: UrlValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
app/forms/url_validator.rb

Overview

A custom validator to check that the field value is a URL.

validates :my_url, url: true

Instance Method Summary collapse

Instance Method Details

#url_valid?(url) ⇒ Boolean

a URL may be technically well-formed but may not actually be valid, so this checks for both.

Returns:

  • (Boolean)


14
15
16
17
18
19
20
21
# File 'app/forms/url_validator.rb', line 14

def url_valid?(url)
  return true if url.blank?

  url = URI.parse(url)
  (url.is_a?(URI::HTTP) || url.is_a?(URI::HTTPS)) && url.host.present?
rescue URI::InvalidURIError
  false
end

#validate_each(record, attribute, value) ⇒ Object



8
9
10
# File 'app/forms/url_validator.rb', line 8

def validate_each(record, attribute, value)
  record.errors[attribute] << (options[:message] || "must be a valid URL") unless url_valid?(value)
end