Class: SizeValidator
- Inherits:
-
ActiveModel::EachValidator
- Object
- ActiveModel::EachValidator
- SizeValidator
- 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
-
#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, 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 [: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 sizeable" end end |