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