summaryrefslogtreecommitdiff
path: root/app/validators
diff options
context:
space:
mode:
authorGitLab Bot <gitlab-bot@gitlab.com>2022-08-26 14:36:54 +0000
committerGitLab Bot <gitlab-bot@gitlab.com>2022-08-26 14:36:54 +0000
commitdaf5ae5bd439f1f32363d410129d5b9e73fbb539 (patch)
tree6d670487dc3dccf1a0c3e6b8337e5b4ab9da4ee9 /app/validators
parent6e8c2290dab8ae1612dff80e312911bc1147edaa (diff)
downloadgitlab-ce-daf5ae5bd439f1f32363d410129d5b9e73fbb539.tar.gz
Add latest changes from gitlab-org/security/gitlab@15-3-stable-ee
Diffstat (limited to 'app/validators')
-rw-r--r--app/validators/bytesize_validator.rb30
1 files changed, 30 insertions, 0 deletions
diff --git a/app/validators/bytesize_validator.rb b/app/validators/bytesize_validator.rb
new file mode 100644
index 00000000000..adbdd81d5c4
--- /dev/null
+++ b/app/validators/bytesize_validator.rb
@@ -0,0 +1,30 @@
+# frozen_string_literal: true
+
+# BytesizeValidator
+#
+# Custom validator for verifying that bytesize of a field doesn't exceed the specified limit.
+# It is different from Rails length validator because it takes .bytesize into account instead of .size/.length
+#
+# Example:
+#
+# class Snippet < ActiveRecord::Base
+# validates :content, bytesize: { maximum: -> { Gitlab::CurrentSettings.snippet_size_limit } }
+# end
+#
+# Configuration options:
+# * <tt>maximum</tt> - Proc that evaluates the bytesize limit that cannot be exceeded
+class BytesizeValidator < ActiveModel::EachValidator
+ def validate_each(record, attr, value)
+ size = value.to_s.bytesize
+ max_size = options[:maximum].call
+
+ return if size <= max_size
+
+ error_message = format(_('is too long (%{size}). The maximum size is %{max_size}.'), {
+ size: ActiveSupport::NumberHelper.number_to_human_size(size),
+ max_size: ActiveSupport::NumberHelper.number_to_human_size(max_size)
+ })
+
+ record.errors.add(attr, error_message)
+ end
+end