2019-05-02 17:17:27 -05:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2019-10-01 23:01:53 -05:00
|
|
|
class StrippedLengthValidator < ActiveModel::EachValidator
|
2013-06-13 03:18:17 -05:00
|
|
|
def self.validate(record, attribute, value, range)
|
2023-01-04 16:08:43 -06:00
|
|
|
if value.nil?
|
2023-01-09 06:10:19 -06:00
|
|
|
record.errors.add attribute, I18n.t("errors.messages.blank")
|
2023-01-04 16:08:43 -06:00
|
|
|
elsif value.length > range.end
|
2023-01-09 06:10:19 -06:00
|
|
|
record.errors.add attribute,
|
|
|
|
I18n.t(
|
|
|
|
"errors.messages.too_long_validation",
|
2024-04-04 08:02:09 -05:00
|
|
|
count: range.end,
|
2023-01-09 06:10:19 -06:00
|
|
|
length: value.length,
|
|
|
|
)
|
2013-02-15 19:58:33 -06:00
|
|
|
else
|
2023-01-04 16:08:43 -06:00
|
|
|
value = get_sanitized_value(value)
|
|
|
|
|
|
|
|
if value.length < range.begin
|
2023-01-09 06:10:19 -06:00
|
|
|
record.errors.add attribute, I18n.t("errors.messages.too_short", count: range.begin)
|
2023-01-04 16:08:43 -06:00
|
|
|
end
|
2013-02-15 19:58:33 -06:00
|
|
|
end
|
|
|
|
end
|
2013-06-13 03:18:17 -05:00
|
|
|
|
|
|
|
def validate_each(record, attribute, value)
|
|
|
|
# the `in` parameter might be a lambda when the range is dynamic
|
|
|
|
range = options[:in].lambda? ? options[:in].call : options[:in]
|
|
|
|
self.class.validate(record, attribute, value, range)
|
|
|
|
end
|
2021-03-31 20:16:18 -05:00
|
|
|
|
|
|
|
def self.get_sanitized_value(value)
|
|
|
|
value = value.dup
|
2023-01-09 06:10:19 -06:00
|
|
|
value.gsub!(/<!--(.*?)-->/, "") # strip HTML comments
|
2021-03-31 20:16:18 -05:00
|
|
|
value.gsub!(/:\w+(:\w+)?:/, "X") # replace emojis with a single character
|
2023-01-09 06:10:19 -06:00
|
|
|
value.gsub!(/\.{2,}/, "…") # replace multiple ... with …
|
|
|
|
value.gsub!(/\,{2,}/, ",") # replace multiple ,,, with ,
|
2021-03-31 20:16:18 -05:00
|
|
|
value.strip
|
|
|
|
end
|
2013-02-15 19:58:33 -06:00
|
|
|
end
|