0
0
RailsHow-ToBeginner · 3 min read

How to Use Length Validation in Ruby on Rails Models

In Ruby on Rails, use validates :attribute, length: { options } inside your model to enforce length rules on strings. You can specify options like minimum, maximum, or is to control the allowed length of the attribute.
📐

Syntax

The length validation in Rails checks the size of a string attribute. You use it inside a model with validates followed by the attribute name and a length hash specifying rules.

  • minimum: sets the smallest allowed length
  • maximum: sets the largest allowed length
  • is: requires the length to be exactly this number
  • within: or in: specify a range of allowed lengths
ruby
validates :attribute_name, length: { minimum: 3, maximum: 10 }
💻

Example

This example shows a User model where the username must be between 4 and 12 characters, and the password must be exactly 8 characters long.

ruby
class User < ApplicationRecord
  validates :username, length: { minimum: 4, maximum: 12 }
  validates :password, length: { is: 8 }
end

# Usage example
user = User.new(username: "bob", password: "12345678")
user.valid? # => false because username is too short
user.errors.full_messages # => ["Username is too short (minimum is 4 characters)"]

user.username = "bobby123"
user.valid? # => true

user.password = "1234"
user.valid? # => false because password length is not 8
user.errors.full_messages # => ["Password is the wrong length (should be 8 characters)"]
Output
false ["Username is too short (minimum is 4 characters)"] true false ["Password is the wrong length (should be 8 characters)"]
⚠️

Common Pitfalls

Common mistakes include:

  • Using length validation on non-string attributes, which may cause unexpected behavior.
  • Forgetting to check valid? before saving, so invalid data gets saved.
  • Mixing minimum and maximum incorrectly or using is with a range.

Always ensure the attribute is a string and test validations properly.

ruby
class Product < ApplicationRecord
  # Wrong: using 'is' with a range
  validates :code, length: { is: 5..10 } # This will cause an error

  # Right:
  validates :code, length: { within: 5..10 }
end
📊

Quick Reference

OptionDescriptionExample
minimumMinimum length allowedvalidates :name, length: { minimum: 3 }
maximumMaximum length allowedvalidates :name, length: { maximum: 10 }
isExact length requiredvalidates :code, length: { is: 5 }
within / inRange of allowed lengthsvalidates :title, length: { within: 4..12 }

Key Takeaways

Use validates :attribute, length: { minimum:, maximum:, is:, within: } inside models to enforce string length.
Check valid? and errors to handle validation feedback before saving records.
Avoid using length validation on non-string attributes to prevent errors.
Use within or in for ranges, not is with ranges.
Length validation helps keep data clean by restricting attribute sizes easily.