0
0
Ruby on Railsframework~5 mins

Length validation in Ruby on Rails

Choose your learning style9 modes available
Introduction

Length validation helps make sure text data is not too short or too long. It keeps your app's data clean and useful.

When you want a username to be at least 3 characters and no more than 15 characters.
When a password must have a minimum length for security reasons.
When a comment should not exceed a certain number of characters to keep it readable.
When a postal code must have an exact length.
When you want to limit the size of a description field to avoid database issues.
Syntax
Ruby on Rails
validates :attribute_name, length: { minimum: x, maximum: y, is: z }

You can use minimum to set the shortest allowed length.

You can use maximum to set the longest allowed length.

Use is for exact length.

Examples
Username must be between 3 and 15 characters.
Ruby on Rails
validates :username, length: { minimum: 3, maximum: 15 }
Password must be at least 8 characters long.
Ruby on Rails
validates :password, length: { minimum: 8 }
Code must be exactly 5 characters.
Ruby on Rails
validates :code, length: { is: 5 }
Sample Program

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.