2019-05-03 06:17:27 +08:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2019-10-02 12:01:53 +08:00
|
|
|
class StrippedLengthValidator < ActiveModel::EachValidator
|
2013-06-13 16:18:17 +08:00
|
|
|
def self.validate(record, attribute, value, range)
|
2024-05-08 00:06:16 +08:00
|
|
|
if value.blank?
|
2023-01-05 06:08:43 +08:00
|
|
|
record.errors.add attribute, I18n.t("errors.messages.blank")
|
|
|
|
elsif value.length > range.end
|
|
|
|
record.errors.add attribute,
|
|
|
|
I18n.t(
|
|
|
|
"errors.messages.too_long_validation",
|
2024-04-04 21:02:09 +08:00
|
|
|
count: range.end,
|
2023-01-05 06:08:43 +08:00
|
|
|
length: value.length,
|
|
|
|
)
|
2013-02-16 09:58:33 +08:00
|
|
|
else
|
2023-01-05 06:08:43 +08:00
|
|
|
value = get_sanitized_value(value)
|
|
|
|
|
|
|
|
if value.length < range.begin
|
|
|
|
record.errors.add attribute, I18n.t("errors.messages.too_short", count: range.begin)
|
|
|
|
end
|
2013-02-16 09:58:33 +08:00
|
|
|
end
|
|
|
|
end
|
2013-06-13 16:18:17 +08: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-04-01 09:16:18 +08:00
|
|
|
|
|
|
|
def self.get_sanitized_value(value)
|
|
|
|
value = value.dup
|
|
|
|
value.gsub!(/<!--(.*?)-->/, "") # strip HTML comments
|
|
|
|
value.gsub!(/:\w+(:\w+)?:/, "X") # replace emojis with a single character
|
|
|
|
value.gsub!(/\.{2,}/, "…") # replace multiple ... with …
|
|
|
|
value.gsub!(/\,{2,}/, ",") # replace multiple ,,, with ,
|
|
|
|
value.strip
|
|
|
|
end
|
2013-02-16 09:58:33 +08:00
|
|
|
end
|