BigW Consortium Gitlab

addressable_url_validator.rb 1.28 KB
Newer Older
1
# AddressableUrlValidator
2
#
3 4 5
# Custom validator for URLs. This is a stricter version of UrlValidator - it also checks
# for using the right protocol, but it actually parses the URL checking for any syntax errors.
# The regex is also different from `URI` as we use `Addressable::URI` here.
6
#
7
# By default, only URLs for http, https, ssh, and git protocols will be considered valid.
8 9 10 11 12
# Provide a `:protocols` option to configure accepted protocols.
#
# Example:
#
#   class User < ActiveRecord::Base
13
#     validates :personal_url, addressable_url: true
14
#
15
#     validates :ftp_url, addressable_url: { protocols: %w(ftp) }
16
#
17
#     validates :git_url, addressable_url: { protocols: %w(http https ssh git) }
18 19 20
#   end
#
class AddressableUrlValidator < ActiveModel::EachValidator
21 22
  DEFAULT_OPTIONS = { protocols: %w(http https ssh git) }

23 24 25 26 27 28
  def validate_each(record, attribute, value)
    unless valid_url?(value)
      record.errors.add(attribute, "must be a valid URL")
    end
  end

29 30
  private

31 32 33
  def valid_url?(value)
    return false unless value

34
    valid_protocol?(value) && valid_uri?(value)
35 36 37
  end

  def valid_uri?(value)
38
    Gitlab::UrlSanitizer.valid?(value)
39 40 41
  end

  def valid_protocol?(value)
42 43
    options = DEFAULT_OPTIONS.merge(self.options)
    value =~ /\A#{URI.regexp(options[:protocols])}\z/
44 45
  end
end