This example shows a User model with length validations on username and password. It creates three users to test the rules and prints if they are valid and their error messages.
Ruby on Rails
class User < ApplicationRecord
validates :username, length: { minimum: 3, maximum: 10 }
validates :password, length: { minimum: 6 }
end
user1 = User.new(username: "Jo", password: "secret")
user2 = User.new(username: "Jonathan", password: "pass")
user3 = User.new(username: "Alice", password: "mypassword")
puts user1.valid? # false because username too short
puts user1.errors.full_messages
puts user2.valid? # false because password too short
puts user2.errors.full_messages
puts user3.valid? # true, all lengths okay
puts user3.errors.full_messages
OutputSuccess
Important Notes
Length validation only checks string length, not content.
Use allow_nil: true if you want to skip validation when the field is empty.
Validation errors help users fix input mistakes.
Summary
Length validation controls how long text fields can be.
Use minimum, maximum, or is options.
It helps keep data clean and user input correct.
Practice
(1/5)
1. What does the length validation in Rails do?
easy
A. It checks how many characters a text field contains.
B. It validates the numerical value of a field.
C. It ensures a field is not empty.
D. It checks if a field contains only letters.
Solution
Step 1: Understand the purpose of length validation
Length validation controls the number of characters allowed in a text field.
Step 2: Compare options with this purpose
Only It checks how many characters a text field contains. matches this description exactly.
Final Answer:
It checks how many characters a text field contains. -> Option A
Quick Check:
Length validation = character count check [OK]
Hint: Length validation controls character count in text fields [OK]
Common Mistakes:
Confusing length with numerical value validation
Thinking it checks for empty fields
Assuming it validates character types
2. Which of the following is the correct syntax to validate that a username has a minimum length of 5 characters in Rails?