instance method
validates_length_of
Ruby on Rails 8.1.2
Since v3.0.20Signature
validates_length_of(*attr_names)
Validates that the specified attributes match the length restrictions supplied. Only one constraint option can be used at a time apart from :minimum and :maximum that can be combined together:
class Person < ActiveRecord::Base validates_length_of :first_name, maximum: 30 validates_length_of :last_name, maximum: 30, message: "less than 30 if you don't mind" validates_length_of :fax, in: 7..32, allow_nil: true validates_length_of :phone, in: 7..32, allow_blank: true validates_length_of :user_name, within: 6..20, too_long: 'pick a shorter name', too_short: 'pick a longer name' validates_length_of :zip_code, minimum: 5, too_short: 'please enter at least 5 characters' validates_length_of :smurf_leader, is: 4, message: "papa is spelled with 4 characters... don't play me." validates_length_of :words_in_essay, minimum: 100, too_short: 'Your essay must be at least 100 words.' private def words_in_essay essay.scan(/\w+/) end end
Constraint options:
-
:minimum- The minimum size of the attribute. -
:maximum- The maximum size of the attribute. Allowsnilby default if not used with:minimum. -
:is- The exact size of the attribute. -
:within- A range specifying the minimum and maximum size of the attribute. -
:in- A synonym (or alias) for:within.
Other options:
-
:allow_nil- Attribute may benil; skip validation. -
:allow_blank- Attribute may be blank; skip validation. -
:too_long- The error message if the attribute goes over the maximum (default is: “is too long (maximum is %{count} characters)”). -
:too_short- The error message if the attribute goes under the minimum (default is: “is too short (minimum is %{count} characters)”). -
:wrong_length- The error message if using the:ismethod and the attribute is the wrong size (default is: “is the wrong length (should be %{count} characters)”). -
:message- The error message to use for a:minimum,:maximum, or:isviolation. An alias of the appropriatetoo_long/too_short/wrong_lengthmessage.
There is also a list of default options supported by every validator: :if, :unless, :on, and :strict. See ActiveModel::Validations::ClassMethods#validates for more information.
Parameters
-
attr_namesrest
Source
# File activemodel/lib/active_model/validations/length.rb, line 123
def validates_length_of(*attr_names)
validates_with LengthValidator, _merge_attributes(attr_names)
end
Defined in activemodel/lib/active_model/validations/length.rb line 123
· View on GitHub
· Improve this page
· Find usages on GitHub
Defined in ActiveModel::Validations::HelperMethods