module ActiveModel::Validations::HelperMethods
def validates_length_of(*attr_names)
+:if+, +:unless+, +:on+, and +:strict+.
There is also a list of default options supported by every validator:
too_long/too_short/wrong_length message.
:maximum, or :is violation. An alias of the appropriate
* :message - The error message to use for a :minimum,
length (should be %{count} characters)").
method and the attribute is the wrong size (default is: "is the wrong
* :wrong_length - The error message if using the :is
minimum (default is: "is too short (minimum is %{count} characters)").
* :too_short - The error message if the attribute goes under the
maximum (default is: "is too long (maximum is %{count} characters)").
* :too_long - The error message if the attribute goes over the
* :allow_blank - Attribute may be blank; skip validation.
* :allow_nil - Attribute may be +nil+; skip validation.
Other options:
* :in - A synonym (or alias) for :within.
the attribute.
* :within - A range specifying the minimum and maximum size of
* :is - The exact size of the attribute.
default if not used with +:minimum+.
* :maximum - The maximum size of the attribute. Allows +nil+ by
* :minimum - The minimum size of the attribute.
Constraint options:
end
end
essay.scan(/\w+/)
def words_in_essay
private
validates_length_of :words_in_essay, minimum: 100, too_short: 'Your essay must be at least 100 words.'
validates_length_of :smurf_leader, is: 4, message: "papa is spelled with 4 characters... don't play me."
validates_length_of :zip_code, minimum: 5, too_short: 'please enter at least 5 characters'
validates_length_of :user_name, within: 6..20, too_long: 'pick a shorter name', too_short: 'pick a longer name'
validates_length_of :phone, in: 7..32, allow_blank: true
validates_length_of :fax, in: 7..32, allow_nil: true
validates_length_of :last_name, maximum: 30, message: "less than 30 if you don't mind"
validates_length_of :first_name, maximum: 30
class Person < ActiveRecord::Base
+:minimum+ and +:maximum+ that can be combined together:
supplied. Only one constraint option can be used at a time apart from
Validates that the specified attributes match the length restrictions
def validates_length_of(*attr_names) validates_with LengthValidator, _merge_attributes(attr_names) end