2019-05-02 18:17:27 -04:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2016-08-16 12:34:04 -04:00
|
|
|
class UrlValidator < ActiveModel::EachValidator
|
|
|
|
def validate_each(record, attribute, value)
|
|
|
|
if value.present?
|
2017-12-20 23:27:17 -05:00
|
|
|
valid =
|
|
|
|
begin
|
|
|
|
uri = URI.parse(value)
|
|
|
|
uri.is_a?(URI::HTTP) && !uri.host.nil? && uri.host.include?(".")
|
2018-08-14 06:23:32 -04:00
|
|
|
rescue URI::Error => e
|
2017-12-21 01:22:55 -05:00
|
|
|
if (e.message =~ /URI must be ascii only/)
|
|
|
|
value = URI.encode(value)
|
|
|
|
retry
|
|
|
|
end
|
|
|
|
|
2017-12-20 23:27:17 -05:00
|
|
|
nil
|
|
|
|
end
|
2016-08-16 12:34:04 -04:00
|
|
|
|
2017-12-20 23:27:17 -05:00
|
|
|
unless valid
|
2019-04-30 02:58:18 -04:00
|
|
|
record.errors.add(attribute, options[:message] || I18n.t('errors.messages.invalid'))
|
2016-08-16 12:34:04 -04:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|