Ruby on Rails ActiveRecord Validations Validating length of an attribute


Example

class Person < ApplicationRecord
  validates :name, length: { minimum: 2 }
  validates :bio, length: { maximum: 500 }
  validates :password, length: { in: 6..20 }
  validates :registration_number, length: { is: 6 }
end

The possible length constraint options are:

  • :minimum - The attribute cannot have less than the specified length.
  • :maximum - The attribute cannot have more than the specified length.
  • :in (or :within) - The attribute length must be included in a given interval. The value for this option must be a range.
  • :is - The attribute length must be equal to the given value.