discourse/lib/validators/stripped_length_validator.rb
Ted Johansson 997a9e3de9
FEATURE: Allow excluding uploads from min post length requirement (#31194)
Currently, the markdown for uploads is counted towards post minimum length requirements. This change introduces a site setting `prevent_uploads_only_posts` which can be flipped to exclude upload segments from the calculation.
2025-02-06 10:26:23 +08:00

40 lines
1.4 KiB
Ruby

# frozen_string_literal: true
class StrippedLengthValidator < ActiveModel::EachValidator
def self.validate(record, attribute, value, range, strip_uploads: false)
if value.blank?
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",
count: range.end,
length: value.length,
)
else
value = get_sanitized_value(value, strip_uploads:)
if value.length < range.begin
record.errors.add attribute, I18n.t("errors.messages.too_short", count: range.begin)
end
end
end
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
def self.get_sanitized_value(value, strip_uploads: false)
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.gsub!(/!\[.*\]\(.+\)/, "") if strip_uploads
value.strip
end
end