1# frozen_string_literal: true 2 3module Gitlab 4 module Search 5 module AbuseValidators 6 class NoAbusiveTermLengthValidator < ActiveModel::EachValidator 7 def validate_each(instance, attribute, value) 8 return unless value.is_a?(String) 9 10 if value.split.any? { |term| term_too_long?(term) } 11 instance.errors.add attribute, 'abusive term length detected' 12 end 13 end 14 15 private 16 17 def term_too_long?(term) 18 char_limit = url_detected?(term) ? maximum_for_url : maximum 19 term.length >= char_limit 20 end 21 22 def url_detected?(uri_str) 23 URI::DEFAULT_PARSER.regexp[:ABS_URI].match? uri_str 24 end 25 26 def maximum_for_url 27 options.fetch(:maximum_for_url, maximum) 28 end 29 30 def maximum 31 options.fetch(:maximum) 32 end 33 end 34 end 35 end 36end 37