Class: BytesizeValidator
- Inherits:
-
ActiveModel::EachValidator
- Object
- ActiveModel::EachValidator
- BytesizeValidator
- Defined in:
- app/validators/bytesize_validator.rb
Overview
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:
-
maximum
- Proc that evaluates the bytesize limit that cannot be exceeded
Instance Method Summary collapse
Instance Method Details
#validate_each(record, attr, value) ⇒ Object
17 18 19 20 21 22 23 24 25 26 27 28 29 |
# File 'app/validators/bytesize_validator.rb', line 17 def validate_each(record, attr, value) size = value.to_s.bytesize max_size = [:maximum].call return if size <= max_size = 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, ) end |