Class: AttrValidator::Validators::LengthValidator

Inherits:
Object
  • Object
show all
Defined in:
lib/attr_validator/validators/length_validator.rb

Class Method Summary collapse

Class Method Details

.validate(object, options) ⇒ Array

Validates that given object has correct length

Parameters:

  • object (#length)

    object to validate

  • options (Hash)

    validation options, e.g. { min: 2, max: 4, equal_to: 3, not_equal_to: 6 }

Returns:

  • (Array)

    empty array if object is valid, array of error messages otherwise



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/attr_validator/validators/length_validator.rb', line 7

def self.validate(object, options)
  return [] if object.nil?

  errors = []
  if options[:min]
    errors << AttrValidator::I18n.t('errors.can_not_be_less_than', length: options[:min]) if object.length < options[:min]
  end
  if options[:max]
    errors << AttrValidator::I18n.t('errors.can_not_be_more_than', length: options[:max]) if object.length > options[:max]
  end
  if options[:equal_to]
    errors << AttrValidator::I18n.t('errors.should_be_equal_to', length: options[:equal_to]) if object.length != options[:equal_to]
  end
  if options[:not_equal_to]
    errors << AttrValidator::I18n.t('errors.should_not_be_equal_to', length: options[:not_equal_to]) if object.length == options[:not_equal_to]
  end

  errors
end

.validate_options(options) ⇒ Object



27
28
29
30
# File 'lib/attr_validator/validators/length_validator.rb', line 27

def self.validate_options(options)
  AttrValidator::ArgsValidator.is_hash!(options, :validation_rule)
  AttrValidator::ArgsValidator.has_only_allowed_keys!(options, [:min, :max, :equal_to, :not_equal_to], :validation_rule)
end