Class: ArrayValidator
- Inherits:
-
ActiveModel::EachValidator
- Object
- ActiveModel::EachValidator
- ArrayValidator
- Defined in:
- lib/array_validator.rb
Overview
A validator to validate the length of an array. Only works on values that are arrays. (Not relationships in Rails 4)
Instance Method Summary collapse
-
#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.
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, array: {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/array_validator.rb', line 9 def validate_each(record, attribute, value) if value.is_a? Array if [:min].present? && value.size < [:min] record.errors.add attribute, [:min_message] || "must have at least #{[:min]} #{'item'.pluralize([:min])}" end if [:max].present? && value.size > [:max] record.errors.add attribute, [:max_message] || "must have at most #{[:max]} #{'item'.pluralize([:max])}" end else record.errors.add attribute, "must be an array" end end |