Class: SizeValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
lib/size_validator.rb

Overview

A validator to validate the length of an array. Works on a collection proxy (has_many relationship) too.

Instance Method Summary collapse

Instance Method Details

#validate_each(record, attribute, value) ⇒ Object

Validate the value is an Array and optionally that the number of items in it is at least a minimum or at most a maximum.

Example:

validates :address_states, size: {min: 1, min_message: "must have at least 1 State selected"},


9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/size_validator.rb', line 9

def validate_each(record, attribute, value)
  if value.respond_to?(:size)
    if options[:min].present? && value.size < options[:min]
      record.errors.add attribute, options[:min_message] || "must have at least #{options[:min]} #{'item'.pluralize(options[:min])}"
    end

    if options[:max].present? && value.size > options[:max]
      record.errors.add attribute, options[:max_message] || "must have at most #{options[:max]} #{'item'.pluralize(options[:max])}"
    end
  else
    record.errors.add attribute, "must be sizeable"
  end
end